From 3168c4ff42c4d1eaa5caa87c8768af2939fd7566 Mon Sep 17 00:00:00 2001 From: Bryntet Date: Thu, 22 Aug 2024 13:39:51 +0200 Subject: [PATCH 1/8] Update CONTRIBUTING.md The message was a bit to vague before --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9ad4b7ab9..77924cd74 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -22,7 +22,7 @@ There are several ways you can contribute to Pumpkin: If you'd like to contribute code changes, fork the Pumpkin repository on GitHub. Install Rust at [rust-lang.org](https://www.rust-lang.org/). Make your changes on your local fork and create a pull request to the main repository. - Ensure your code adheres to the project's coding style guidelines (if any). + Ensure your code adheres to our project structure and style guidlines. Write clear and concise commit messages that describe your changes. ### Project Structure From dda60d67a7b679bd60df5932de9d86c9346471d9 Mon Sep 17 00:00:00 2001 From: Bryntet Date: Fri, 23 Aug 2024 12:14:32 +0200 Subject: [PATCH 2/8] Update CONTRIBUTING.md --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 77924cd74..9bca5c2e3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -22,7 +22,7 @@ There are several ways you can contribute to Pumpkin: If you'd like to contribute code changes, fork the Pumpkin repository on GitHub. Install Rust at [rust-lang.org](https://www.rust-lang.org/). Make your changes on your local fork and create a pull request to the main repository. - Ensure your code adheres to our project structure and style guidlines. + Ensure your code adheres to our project structure and style guidelines. Write clear and concise commit messages that describe your changes. ### Project Structure From 0ce03c0497b0e60770e416cfe57126ac7cc468b2 Mon Sep 17 00:00:00 2001 From: Snowiiii Date: Sun, 25 Aug 2024 09:37:58 +0200 Subject: [PATCH 3/8] Support Transfer --- pumpkin-protocol/src/server/play/s_set_creative_slot.rs | 1 - pumpkin/src/client/client_packet.rs | 4 ++-- pumpkin/src/client/mod.rs | 4 +++- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/pumpkin-protocol/src/server/play/s_set_creative_slot.rs b/pumpkin-protocol/src/server/play/s_set_creative_slot.rs index 8f1c7a522..ce0b7490d 100644 --- a/pumpkin-protocol/src/server/play/s_set_creative_slot.rs +++ b/pumpkin-protocol/src/server/play/s_set_creative_slot.rs @@ -3,7 +3,6 @@ use pumpkin_macros::packet; use crate::slot::Slot; #[derive(serde::Deserialize, Debug)] -#[allow(dead_code)] #[packet(0x32)] pub struct SSetCreativeSlot { pub slot: i16, diff --git a/pumpkin/src/client/client_packet.rs b/pumpkin/src/client/client_packet.rs index 442565b5b..d93e72a30 100644 --- a/pumpkin/src/client/client_packet.rs +++ b/pumpkin/src/client/client_packet.rs @@ -36,7 +36,7 @@ impl Client { dbg!("handshake"); self.protocol_version = handshake.protocol_version.0; self.connection_state = handshake.next_state; - if self.connection_state == ConnectionState::Login { + if self.connection_state != ConnectionState::Status { let protocol = self.protocol_version; match protocol.cmp(&(CURRENT_MC_PROTOCOL as i32)) { std::cmp::Ordering::Less => { @@ -65,7 +65,7 @@ impl Client { } pub fn handle_login_start(&mut self, server: &mut Server, login_start: SLoginStart) { - dbg!("login start"); + log::debug!("login start, State {:?}", self.connection_state); if !Self::is_valid_player_name(&login_start.name) { self.kick("Invalid characters in username"); diff --git a/pumpkin/src/client/mod.rs b/pumpkin/src/client/mod.rs index 4744594e8..f90b97b7f 100644 --- a/pumpkin/src/client/mod.rs +++ b/pumpkin/src/client/mod.rs @@ -180,7 +180,9 @@ impl Client { packet.id.0 ), }, - pumpkin_protocol::ConnectionState::Login => match packet.id.0 { + // TODO: Check config if transfer is enabled + pumpkin_protocol::ConnectionState::Login + | pumpkin_protocol::ConnectionState::Transfer => match packet.id.0 { SLoginStart::PACKET_ID => { self.handle_login_start(server, SLoginStart::read(bytebuf).unwrap()) } From 020c71a97349e9fb19b90b1c17f78adc8d520999 Mon Sep 17 00:00:00 2001 From: Snowiiii Date: Sun, 25 Aug 2024 11:02:40 +0200 Subject: [PATCH 4/8] Remove unwarp when reading packets --- pumpkin/src/client/mod.rs | 134 ++++++++++++++++++++++------------- pumpkin/src/entity/player.rs | 82 ++++++++++++++------- 2 files changed, 139 insertions(+), 77 deletions(-) diff --git a/pumpkin/src/client/mod.rs b/pumpkin/src/client/mod.rs index f90b97b7f..43a10ff0c 100644 --- a/pumpkin/src/client/mod.rs +++ b/pumpkin/src/client/mod.rs @@ -1,5 +1,4 @@ use std::{ - collections::VecDeque, io::{self, Write}, net::SocketAddr, rc::Rc, @@ -14,7 +13,7 @@ use authentication::GameProfile; use mio::{event::Event, net::TcpStream, Token}; use pumpkin_core::text::TextComponent; use pumpkin_protocol::{ - bytebuf::packet_id::Packet, + bytebuf::{packet_id::Packet, DeserializerError}, client::{config::CConfigDisconnect, login::CLoginDisconnect, play::CPlayDisconnect}, packet_decoder::PacketDecoder, packet_encoder::PacketEncoder, @@ -76,7 +75,7 @@ pub struct Client { pub address: SocketAddr, enc: PacketEncoder, dec: PacketDecoder, - pub client_packets_queue: VecDeque, + pub client_packets_queue: Vec, pub make_player: bool, } @@ -96,14 +95,14 @@ impl Client { dec: PacketDecoder::default(), encryption: true, closed: false, - client_packets_queue: VecDeque::new(), + client_packets_queue: Vec::new(), make_player: false, } } /// adds a Incoming packet to the queue pub fn add_packet(&mut self, packet: RawPacket) { - self.client_packets_queue.push_back(packet); + self.client_packets_queue.push(packet); } /// enables encryption @@ -146,86 +145,121 @@ impl Client { } pub async fn process_packets(&mut self, server: &mut Server) { - let mut i = 0; - while i < self.client_packets_queue.len() { - let mut packet = self.client_packets_queue.remove(i).unwrap(); - self.handle_packet(server, &mut packet).await; - i += 1; + while let Some(mut packet) = self.client_packets_queue.pop() { + match self.handle_packet(server, &mut packet).await { + Ok(_) => {} + Err(e) => { + let text = format!("Error while reading incoming packet {}", e); + log::error!("{}", text); + self.kick(&text) + } + }; } } /// Handles an incoming decoded not Play state Packet - pub async fn handle_packet(&mut self, server: &mut Server, packet: &mut RawPacket) { + pub async fn handle_packet( + &mut self, + server: &mut Server, + packet: &mut RawPacket, + ) -> Result<(), DeserializerError> { // TODO: handle each packet's Error instead of calling .unwrap() let bytebuf = &mut packet.bytebuf; match self.connection_state { pumpkin_protocol::ConnectionState::HandShake => match packet.id.0 { SHandShake::PACKET_ID => { - self.handle_handshake(server, SHandShake::read(bytebuf).unwrap()) + self.handle_handshake(server, SHandShake::read(bytebuf)?); + Ok(()) + } + _ => { + log::error!( + "Failed to handle packet id {} while in Handshake state", + packet.id.0 + ); + Ok(()) } - _ => log::error!( - "Failed to handle packet id {} while in Handshake state", - packet.id.0 - ), }, pumpkin_protocol::ConnectionState::Status => match packet.id.0 { SStatusRequest::PACKET_ID => { - self.handle_status_request(server, SStatusRequest::read(bytebuf).unwrap()) + self.handle_status_request(server, SStatusRequest::read(bytebuf)?); + Ok(()) } SStatusPingRequest::PACKET_ID => { - self.handle_ping_request(server, SStatusPingRequest::read(bytebuf).unwrap()) + self.handle_ping_request(server, SStatusPingRequest::read(bytebuf)?); + Ok(()) + } + _ => { + log::error!( + "Failed to handle packet id {} while in Status state", + packet.id.0 + ); + Ok(()) } - _ => log::error!( - "Failed to handle packet id {} while in Status state", - packet.id.0 - ), }, // TODO: Check config if transfer is enabled pumpkin_protocol::ConnectionState::Login | pumpkin_protocol::ConnectionState::Transfer => match packet.id.0 { SLoginStart::PACKET_ID => { - self.handle_login_start(server, SLoginStart::read(bytebuf).unwrap()) + self.handle_login_start(server, SLoginStart::read(bytebuf)?); + Ok(()) } SEncryptionResponse::PACKET_ID => { - self.handle_encryption_response( - server, - SEncryptionResponse::read(bytebuf).unwrap(), - ) - .await + self.handle_encryption_response(server, SEncryptionResponse::read(bytebuf)?) + .await; + Ok(()) + } + SLoginPluginResponse::PACKET_ID => { + self.handle_plugin_response(server, SLoginPluginResponse::read(bytebuf)?); + Ok(()) + } + SLoginAcknowledged::PACKET_ID => { + self.handle_login_acknowledged(server, SLoginAcknowledged::read(bytebuf)?); + Ok(()) + } + _ => { + log::error!( + "Failed to handle packet id {} while in Login state", + packet.id.0 + ); + Ok(()) } - SLoginPluginResponse::PACKET_ID => self - .handle_plugin_response(server, SLoginPluginResponse::read(bytebuf).unwrap()), - SLoginAcknowledged::PACKET_ID => self - .handle_login_acknowledged(server, SLoginAcknowledged::read(bytebuf).unwrap()), - _ => log::error!( - "Failed to handle packet id {} while in Login state", - packet.id.0 - ), }, pumpkin_protocol::ConnectionState::Config => match packet.id.0 { - SClientInformationConfig::PACKET_ID => self.handle_client_information_config( - server, - SClientInformationConfig::read(bytebuf).unwrap(), - ), + SClientInformationConfig::PACKET_ID => { + self.handle_client_information_config( + server, + SClientInformationConfig::read(bytebuf)?, + ); + Ok(()) + } SPluginMessage::PACKET_ID => { - self.handle_plugin_message(server, SPluginMessage::read(bytebuf).unwrap()) + self.handle_plugin_message(server, SPluginMessage::read(bytebuf)?); + Ok(()) } SAcknowledgeFinishConfig::PACKET_ID => { self.handle_config_acknowledged( server, - SAcknowledgeFinishConfig::read(bytebuf).unwrap(), + SAcknowledgeFinishConfig::read(bytebuf)?, ) - .await + .await; + Ok(()) } SKnownPacks::PACKET_ID => { - self.handle_known_packs(server, SKnownPacks::read(bytebuf).unwrap()) + self.handle_known_packs(server, SKnownPacks::read(bytebuf)?); + Ok(()) + } + _ => { + log::error!( + "Failed to handle packet id {} while in Config state", + packet.id.0 + ); + Ok(()) } - _ => log::error!( - "Failed to handle packet id {} while in Config state", - packet.id.0 - ), }, - _ => log::error!("Invalid Connection state {:?}", self.connection_state), + _ => { + log::error!("Invalid Connection state {:?}", self.connection_state); + Ok(()) + } } } @@ -279,7 +313,7 @@ impl Client { match self.connection_state { ConnectionState::Login => { self.try_send_packet(&CLoginDisconnect::new( - &serde_json::to_string_pretty(&reason).unwrap(), + &serde_json::to_string_pretty(&reason).unwrap_or("".into()), )) .unwrap_or_else(|_| self.close()); } diff --git a/pumpkin/src/entity/player.rs b/pumpkin/src/entity/player.rs index 64f46e585..8a8d3471d 100644 --- a/pumpkin/src/entity/player.rs +++ b/pumpkin/src/entity/player.rs @@ -6,7 +6,7 @@ use pumpkin_core::text::TextComponent; use pumpkin_entity::{entity_type::EntityType, Entity, EntityId}; use pumpkin_inventory::player::PlayerInventory; use pumpkin_protocol::{ - bytebuf::packet_id::Packet, + bytebuf::{packet_id::Packet, DeserializerError}, client::play::{CGameEvent, CPlayDisconnect, CSyncPlayerPosition, CSystemChatMessage}, server::play::{ SChatCommand, SChatMessage, SClientInformationPlay, SConfirmTeleport, SInteract, @@ -153,61 +153,89 @@ impl Player { impl Player { pub fn process_packets(&mut self, server: &mut Server) { - let mut i = 0; - while i < self.client.client_packets_queue.len() { - let mut packet = self.client.client_packets_queue.remove(i).unwrap(); - self.handle_play_packet(server, &mut packet); - i += 1; + while let Some(mut packet) = self.client.client_packets_queue.pop() { + match self.handle_play_packet(server, &mut packet) { + Ok(_) => {} + Err(e) => { + let text = format!("Error while reading incoming packet {}", e); + log::error!("{}", text); + self.kick(TextComponent::text(&text)) + } + }; } } - pub fn handle_play_packet(&mut self, server: &mut Server, packet: &mut RawPacket) { + pub fn handle_play_packet( + &mut self, + server: &mut Server, + packet: &mut RawPacket, + ) -> Result<(), DeserializerError> { let bytebuf = &mut packet.bytebuf; match packet.id.0 { SConfirmTeleport::PACKET_ID => { - self.handle_confirm_teleport(server, SConfirmTeleport::read(bytebuf).unwrap()) + self.handle_confirm_teleport(server, SConfirmTeleport::read(bytebuf)?); + Ok(()) } SChatCommand::PACKET_ID => { - self.handle_chat_command(server, SChatCommand::read(bytebuf).unwrap()) + self.handle_chat_command(server, SChatCommand::read(bytebuf)?); + Ok(()) } SPlayerPosition::PACKET_ID => { - self.handle_position(server, SPlayerPosition::read(bytebuf).unwrap()) + self.handle_position(server, SPlayerPosition::read(bytebuf)?); + Ok(()) + } + SPlayerPositionRotation::PACKET_ID => { + self.handle_position_rotation(server, SPlayerPositionRotation::read(bytebuf)?); + Ok(()) } - SPlayerPositionRotation::PACKET_ID => self - .handle_position_rotation(server, SPlayerPositionRotation::read(bytebuf).unwrap()), SPlayerRotation::PACKET_ID => { - self.handle_rotation(server, SPlayerRotation::read(bytebuf).unwrap()) + self.handle_rotation(server, SPlayerRotation::read(bytebuf)?); + Ok(()) } SPlayerCommand::PACKET_ID => { - self.handle_player_command(server, SPlayerCommand::read(bytebuf).unwrap()) + self.handle_player_command(server, SPlayerCommand::read(bytebuf)?); + Ok(()) } SSwingArm::PACKET_ID => { - self.handle_swing_arm(server, SSwingArm::read(bytebuf).unwrap()) + self.handle_swing_arm(server, SSwingArm::read(bytebuf)?); + Ok(()) } SChatMessage::PACKET_ID => { - self.handle_chat_message(server, SChatMessage::read(bytebuf).unwrap()) + self.handle_chat_message(server, SChatMessage::read(bytebuf)?); + Ok(()) + } + SClientInformationPlay::PACKET_ID => { + self.handle_client_information_play(server, SClientInformationPlay::read(bytebuf)?); + Ok(()) + } + SInteract::PACKET_ID => { + self.handle_interact(server, SInteract::read(bytebuf)?); + Ok(()) } - SClientInformationPlay::PACKET_ID => self.handle_client_information_play( - server, - SClientInformationPlay::read(bytebuf).unwrap(), - ), - SInteract::PACKET_ID => self.handle_interact(server, SInteract::read(bytebuf).unwrap()), SPlayerAction::PACKET_ID => { - self.handle_player_action(server, SPlayerAction::read(bytebuf).unwrap()) + self.handle_player_action(server, SPlayerAction::read(bytebuf)?); + Ok(()) } SUseItemOn::PACKET_ID => { - self.handle_use_item_on(server, SUseItemOn::read(bytebuf).unwrap()) + self.handle_use_item_on(server, SUseItemOn::read(bytebuf)?); + Ok(()) } SSetHeldItem::PACKET_ID => { - self.handle_set_held_item(server, SSetHeldItem::read(bytebuf).unwrap()) + self.handle_set_held_item(server, SSetHeldItem::read(bytebuf)?); + Ok(()) } SSetCreativeSlot::PACKET_ID => { - self.handle_set_creative_slot(server, SSetCreativeSlot::read(bytebuf).unwrap()) + self.handle_set_creative_slot(server, SSetCreativeSlot::read(bytebuf)?); + Ok(()) } SPlayPingRequest::PACKET_ID => { - self.handle_play_ping_request(server, SPlayPingRequest::read(bytebuf).unwrap()) + self.handle_play_ping_request(server, SPlayPingRequest::read(bytebuf)?); + Ok(()) + } + _ => { + log::error!("Failed to handle player packet id {:#04x}", packet.id.0); + Ok(()) } - _ => log::error!("Failed to handle player packet id {:#04x}", packet.id.0), } } } From ddd3f1e7813ccfc2076e08ed4eabd59d3302b356 Mon Sep 17 00:00:00 2001 From: Snowiiii Date: Sun, 25 Aug 2024 12:06:09 +0200 Subject: [PATCH 5/8] Add Serverbound Set Player On Ground --- pumpkin-protocol/src/bytebuf/mod.rs | 2 +- pumpkin-protocol/src/client/login/c_login_success.rs | 4 ++-- pumpkin-protocol/src/client/play/c_player_info_update.rs | 2 +- pumpkin-protocol/src/server/play/mod.rs | 2 ++ pumpkin-protocol/src/server/play/s_player_ground.rs | 8 ++++++++ pumpkin/src/client/client_packet.rs | 2 +- pumpkin/src/client/player_packet.rs | 6 +++++- pumpkin/src/entity/player.rs | 6 +++++- 8 files changed, 25 insertions(+), 7 deletions(-) create mode 100644 pumpkin-protocol/src/server/play/s_player_ground.rs diff --git a/pumpkin-protocol/src/bytebuf/mod.rs b/pumpkin-protocol/src/bytebuf/mod.rs index 250d4fa1f..d6be909de 100644 --- a/pumpkin-protocol/src/bytebuf/mod.rs +++ b/pumpkin-protocol/src/bytebuf/mod.rs @@ -119,7 +119,7 @@ impl ByteBuffer { } } - pub fn put_uuid(&mut self, v: uuid::Uuid) { + pub fn put_uuid(&mut self, v: &uuid::Uuid) { // thats the vanilla way let pair = v.as_u64_pair(); self.put_u64(pair.0); diff --git a/pumpkin-protocol/src/client/login/c_login_success.rs b/pumpkin-protocol/src/client/login/c_login_success.rs index 4177d1c5a..cf0d52ee8 100644 --- a/pumpkin-protocol/src/client/login/c_login_success.rs +++ b/pumpkin-protocol/src/client/login/c_login_success.rs @@ -4,7 +4,7 @@ use crate::{bytebuf::ByteBuffer, ClientPacket, Property}; #[packet(0x02)] pub struct CLoginSuccess<'a> { - pub uuid: uuid::Uuid, + pub uuid: &'a uuid::Uuid, pub username: &'a str, // 16 pub properties: &'a [Property], pub strict_error_handling: bool, @@ -12,7 +12,7 @@ pub struct CLoginSuccess<'a> { impl<'a> CLoginSuccess<'a> { pub fn new( - uuid: uuid::Uuid, + uuid: &'a uuid::Uuid, username: &'a str, properties: &'a [Property], strict_error_handling: bool, diff --git a/pumpkin-protocol/src/client/play/c_player_info_update.rs b/pumpkin-protocol/src/client/play/c_player_info_update.rs index 1be348dc5..e85f2637f 100644 --- a/pumpkin-protocol/src/client/play/c_player_info_update.rs +++ b/pumpkin-protocol/src/client/play/c_player_info_update.rs @@ -25,7 +25,7 @@ impl<'a> ClientPacket for CPlayerInfoUpdate<'a> { fn write(&self, bytebuf: &mut ByteBuffer) { bytebuf.put_i8(self.actions); bytebuf.put_list::(self.players, |p, v| { - p.put_uuid(v.uuid); + p.put_uuid(&v.uuid); for action in &v.actions { match action { PlayerAction::AddPlayer { name, properties } => { diff --git a/pumpkin-protocol/src/server/play/mod.rs b/pumpkin-protocol/src/server/play/mod.rs index 2cccb9c2e..0e2fc9a26 100644 --- a/pumpkin-protocol/src/server/play/mod.rs +++ b/pumpkin-protocol/src/server/play/mod.rs @@ -7,6 +7,7 @@ mod s_interact; mod s_ping_request; mod s_player_action; mod s_player_command; +mod s_player_ground; mod s_player_position; mod s_player_position_rotation; mod s_player_rotation; @@ -24,6 +25,7 @@ pub use s_interact::*; pub use s_ping_request::*; pub use s_player_action::*; pub use s_player_command::*; +pub use s_player_ground::*; pub use s_player_position::*; pub use s_player_position_rotation::*; pub use s_player_rotation::*; diff --git a/pumpkin-protocol/src/server/play/s_player_ground.rs b/pumpkin-protocol/src/server/play/s_player_ground.rs new file mode 100644 index 000000000..915d8614e --- /dev/null +++ b/pumpkin-protocol/src/server/play/s_player_ground.rs @@ -0,0 +1,8 @@ +use pumpkin_macros::packet; +use serde::Deserialize; + +#[derive(Deserialize)] +#[packet(0x1D)] +pub struct SSetPlayerGround { + pub on_ground: bool, +} diff --git a/pumpkin/src/client/client_packet.rs b/pumpkin/src/client/client_packet.rs index d93e72a30..7ba6cfb62 100644 --- a/pumpkin/src/client/client_packet.rs +++ b/pumpkin/src/client/client_packet.rs @@ -175,7 +175,7 @@ impl Client { } if let Some(profile) = self.gameprofile.as_ref().cloned() { - let packet = CLoginSuccess::new(profile.id, &profile.name, &profile.properties, false); + let packet = CLoginSuccess::new(&profile.id, &profile.name, &profile.properties, false); self.send_packet(&packet); } else { self.kick("game profile is none"); diff --git a/pumpkin/src/client/player_packet.rs b/pumpkin/src/client/player_packet.rs index fff71fb08..1d405081d 100644 --- a/pumpkin/src/client/player_packet.rs +++ b/pumpkin/src/client/player_packet.rs @@ -10,7 +10,7 @@ use num_traits::FromPrimitive; use pumpkin_core::text::TextComponent; use pumpkin_entity::EntityId; use pumpkin_inventory::WindowType; -use pumpkin_protocol::server::play::SCloseContainer; +use pumpkin_protocol::server::play::{SCloseContainer, SSetPlayerGround}; use pumpkin_protocol::{ client::play::{ Animation, CAcknowledgeBlockChange, CBlockUpdate, CEntityAnimation, CEntityVelocity, @@ -178,6 +178,10 @@ impl Player { handle_command(&mut CommandSender::Player(self), &command.command); } + pub fn handle_player_ground(&mut self, _server: &mut Server, ground: SSetPlayerGround) { + self.on_ground = ground.on_ground; + } + pub fn handle_player_command(&mut self, _server: &mut Server, command: SPlayerCommand) { if command.entity_id != self.entity.entity_id.into() { return; diff --git a/pumpkin/src/entity/player.rs b/pumpkin/src/entity/player.rs index 8a8d3471d..9925278ee 100644 --- a/pumpkin/src/entity/player.rs +++ b/pumpkin/src/entity/player.rs @@ -11,7 +11,7 @@ use pumpkin_protocol::{ server::play::{ SChatCommand, SChatMessage, SClientInformationPlay, SConfirmTeleport, SInteract, SPlayPingRequest, SPlayerAction, SPlayerCommand, SPlayerPosition, SPlayerPositionRotation, - SPlayerRotation, SSetCreativeSlot, SSetHeldItem, SSwingArm, SUseItemOn, + SPlayerRotation, SSetCreativeSlot, SSetHeldItem, SSetPlayerGround, SSwingArm, SUseItemOn, }, ConnectionState, RawPacket, ServerPacket, VarInt, }; @@ -192,6 +192,10 @@ impl Player { self.handle_rotation(server, SPlayerRotation::read(bytebuf)?); Ok(()) } + SSetPlayerGround::PACKET_ID => { + self.handle_player_ground(server, SSetPlayerGround::read(bytebuf)?); + Ok(()) + } SPlayerCommand::PACKET_ID => { self.handle_player_command(server, SPlayerCommand::read(bytebuf)?); Ok(()) From 83aad86005e753d6fb765f236a1d8474f033486e Mon Sep 17 00:00:00 2001 From: Snowiiii Date: Sun, 25 Aug 2024 13:20:49 +0200 Subject: [PATCH 6/8] Made everything thread safe - Also improved gamemode command - We now can use Server in commands --- .../src/client/play/c_player_info_update.rs | 4 +-- .../src/client/play/player_action.rs | 10 +++--- pumpkin/src/client/mod.rs | 5 +-- pumpkin/src/client/player_packet.rs | 4 +-- pumpkin/src/commands/cmd_gamemode.rs | 20 +++++------ pumpkin/src/commands/cmd_help.rs | 4 +-- pumpkin/src/commands/cmd_pumpkin.rs | 2 +- pumpkin/src/commands/cmd_stop.rs | 2 +- pumpkin/src/commands/dispatcher.rs | 13 +++++-- pumpkin/src/commands/mod.rs | 5 +-- pumpkin/src/commands/tree.rs | 4 ++- pumpkin/src/commands/tree_builder.rs | 7 ++-- pumpkin/src/entity/player.rs | 17 ++++++++-- pumpkin/src/main.rs | 34 +++++++++++++------ pumpkin/src/rcon/mod.rs | 19 +++++++---- pumpkin/src/server.rs | 32 ++++++++--------- 16 files changed, 114 insertions(+), 68 deletions(-) diff --git a/pumpkin-protocol/src/client/play/c_player_info_update.rs b/pumpkin-protocol/src/client/play/c_player_info_update.rs index e85f2637f..b62108680 100644 --- a/pumpkin-protocol/src/client/play/c_player_info_update.rs +++ b/pumpkin-protocol/src/client/play/c_player_info_update.rs @@ -37,8 +37,8 @@ impl<'a> ClientPacket for CPlayerInfoUpdate<'a> { }); } PlayerAction::InitializeChat(_) => todo!(), - PlayerAction::UpdateGameMode(_) => todo!(), - PlayerAction::UpdateListed { listed } => p.put_bool(*listed), + PlayerAction::UpdateGameMode(gamemode) => p.put_var_int(gamemode), + PlayerAction::UpdateListed(listed) => p.put_bool(*listed), PlayerAction::UpdateLatency(_) => todo!(), PlayerAction::UpdateDisplayName(_) => todo!(), } diff --git a/pumpkin-protocol/src/client/play/player_action.rs b/pumpkin-protocol/src/client/play/player_action.rs index 2230deacb..3a5f2a80a 100644 --- a/pumpkin-protocol/src/client/play/player_action.rs +++ b/pumpkin-protocol/src/client/play/player_action.rs @@ -1,4 +1,4 @@ -use crate::Property; +use crate::{Property, VarInt}; pub enum PlayerAction { AddPlayer { @@ -6,10 +6,10 @@ pub enum PlayerAction { properties: Vec, }, InitializeChat(u8), - UpdateGameMode(u8), - UpdateListed { - listed: bool, - }, + /// Gamemode ? + UpdateGameMode(VarInt), + /// Listed ? + UpdateListed(bool), UpdateLatency(u8), UpdateDisplayName(u8), } diff --git a/pumpkin/src/client/mod.rs b/pumpkin/src/client/mod.rs index 43a10ff0c..5e7e01224 100644 --- a/pumpkin/src/client/mod.rs +++ b/pumpkin/src/client/mod.rs @@ -2,6 +2,7 @@ use std::{ io::{self, Write}, net::SocketAddr, rc::Rc, + sync::Arc, }; use crate::{ @@ -70,7 +71,7 @@ pub struct Client { pub connection_state: ConnectionState, pub encryption: bool, pub closed: bool, - pub token: Rc, + pub token: Arc, pub connection: TcpStream, pub address: SocketAddr, enc: PacketEncoder, @@ -81,7 +82,7 @@ pub struct Client { } impl Client { - pub fn new(token: Rc, connection: TcpStream, address: SocketAddr) -> Self { + pub fn new(token: Arc, connection: TcpStream, address: SocketAddr) -> Self { Self { protocol_version: 0, gameprofile: None, diff --git a/pumpkin/src/client/player_packet.rs b/pumpkin/src/client/player_packet.rs index 1d405081d..b242f2b6b 100644 --- a/pumpkin/src/client/player_packet.rs +++ b/pumpkin/src/client/player_packet.rs @@ -174,8 +174,8 @@ impl Player { server.broadcast_packet(self, &CHeadRot::new(entity_id.into(), yaw as u8)); } - pub fn handle_chat_command(&mut self, _server: &mut Server, command: SChatCommand) { - handle_command(&mut CommandSender::Player(self), &command.command); + pub fn handle_chat_command(&mut self, server: &mut Server, command: SChatCommand) { + handle_command(&mut CommandSender::Player(self), server, &command.command); } pub fn handle_player_ground(&mut self, _server: &mut Server, ground: SSetPlayerGround) { diff --git a/pumpkin/src/commands/cmd_gamemode.rs b/pumpkin/src/commands/cmd_gamemode.rs index a90de4eba..17f5de91a 100644 --- a/pumpkin/src/commands/cmd_gamemode.rs +++ b/pumpkin/src/commands/cmd_gamemode.rs @@ -60,12 +60,12 @@ pub(crate) fn init_command_tree<'a>() -> CommandTree<'a> { CommandTree::new(NAMES, DESCRIPTION).with_child( require(&|sender| sender.permission_lvl() >= 2).with_child( argument(ARG_GAMEMODE, consume_arg_gamemode) - .with_child( - require(&|sender| sender.is_player()).execute(&|sender, args| { + .with_child(require(&|sender| sender.is_player()).execute( + &|sender, server, args| { let gamemode = parse_arg_gamemode(args)?; return if let Player(target) = sender { - target.set_gamemode(gamemode); + target.set_gamemode(server, gamemode); target.send_system_message(TextComponent::text(&format!( "Game mode was set to {:?}", gamemode @@ -75,22 +75,22 @@ pub(crate) fn init_command_tree<'a>() -> CommandTree<'a> { } else { Err(InvalidRequirementError) }; - }), - ) - .with_child( - argument(ARG_TARGET, consume_arg_player).execute(&|sender, args| { + }, + )) + .with_child(argument(ARG_TARGET, consume_arg_player).execute( + &|sender, server, args| { let gamemode = parse_arg_gamemode(args)?; let target = parse_arg_player(sender, ARG_TARGET, args)?; - target.set_gamemode(gamemode); + target.set_gamemode(server, gamemode); target.send_system_message(TextComponent::text(&format!( "Set own game mode to {:?}", gamemode ))); Ok(()) - }), - ), + }, + )), ), ) } diff --git a/pumpkin/src/commands/cmd_help.rs b/pumpkin/src/commands/cmd_help.rs index 98a8bb22e..8d432a8dd 100644 --- a/pumpkin/src/commands/cmd_help.rs +++ b/pumpkin/src/commands/cmd_help.rs @@ -35,7 +35,7 @@ fn parse_arg_command<'a>( pub(crate) fn init_command_tree<'a>() -> CommandTree<'a> { CommandTree::new(NAMES, DESCRIPTION) .with_child( - argument(ARG_COMMAND, consume_arg_command).execute(&|sender, args| { + argument(ARG_COMMAND, consume_arg_command).execute(&|sender, _, args| { let dispatcher = DISPATCHER.get_or_init(dispatcher_init); let tree = parse_arg_command(args, dispatcher)?; @@ -50,7 +50,7 @@ pub(crate) fn init_command_tree<'a>() -> CommandTree<'a> { Ok(()) }), ) - .execute(&|sender, _args| { + .execute(&|sender, _, _args| { let dispatcher = DISPATCHER.get_or_init(dispatcher_init); let mut keys: Vec<&str> = dispatcher.commands.keys().copied().collect(); diff --git a/pumpkin/src/commands/cmd_pumpkin.rs b/pumpkin/src/commands/cmd_pumpkin.rs index 80347f7cc..ad0b3561e 100644 --- a/pumpkin/src/commands/cmd_pumpkin.rs +++ b/pumpkin/src/commands/cmd_pumpkin.rs @@ -9,7 +9,7 @@ const NAMES: [&str; 1] = ["pumpkin"]; const DESCRIPTION: &str = "Display information about Pumpkin."; pub(crate) fn init_command_tree<'a>() -> CommandTree<'a> { - CommandTree::new(NAMES, DESCRIPTION).execute(&|sender, _| { + CommandTree::new(NAMES, DESCRIPTION).execute(&|sender, _, _| { let version = env!("CARGO_PKG_VERSION"); let description = env!("CARGO_PKG_DESCRIPTION"); diff --git a/pumpkin/src/commands/cmd_stop.rs b/pumpkin/src/commands/cmd_stop.rs index 81bd07ea9..5e12ccb48 100644 --- a/pumpkin/src/commands/cmd_stop.rs +++ b/pumpkin/src/commands/cmd_stop.rs @@ -10,7 +10,7 @@ const DESCRIPTION: &str = "Stop the server."; pub(crate) fn init_command_tree<'a>() -> CommandTree<'a> { CommandTree::new(NAMES, DESCRIPTION).with_child( - require(&|sender| sender.permission_lvl() >= 4).execute(&|sender, _args| { + require(&|sender| sender.permission_lvl() >= 4).execute(&|sender, _, _args| { sender .send_message(TextComponent::text("Stopping Server").color_named(NamedColor::Red)); std::process::exit(0) diff --git a/pumpkin/src/commands/dispatcher.rs b/pumpkin/src/commands/dispatcher.rs index dac9c8894..25e912055 100644 --- a/pumpkin/src/commands/dispatcher.rs +++ b/pumpkin/src/commands/dispatcher.rs @@ -3,6 +3,7 @@ use crate::commands::dispatcher::InvalidTreeError::{ }; use crate::commands::tree::{Command, CommandTree, ConsumedArgs, NodeType, RawArgs}; use crate::commands::CommandSender; +use crate::server::Server; use std::collections::HashMap; #[derive(Debug)] @@ -23,7 +24,12 @@ pub(crate) struct CommandDispatcher<'a> { /// Stores registered [CommandTree]s and dispatches commands to them. impl<'a> CommandDispatcher<'a> { /// Execute a command using its corresponding [CommandTree]. - pub(crate) fn dispatch(&'a self, src: &mut CommandSender, cmd: &str) -> Result<(), String> { + pub(crate) fn dispatch( + &'a self, + src: &mut CommandSender, + server: &mut Server, + cmd: &str, + ) -> Result<(), String> { let mut parts = cmd.split_ascii_whitespace(); let key = parts.next().ok_or("Empty Command")?; let raw_args: Vec<&str> = parts.rev().collect(); @@ -32,7 +38,7 @@ impl<'a> CommandDispatcher<'a> { // try paths until fitting path is found for path in tree.iter_paths() { - match Self::try_is_fitting_path(src, path, tree, raw_args.clone()) { + match Self::try_is_fitting_path(src, server, path, tree, raw_args.clone()) { Err(InvalidConsumptionError(s)) => { println!("Error while parsing command \"{cmd}\": {s:?} was consumed, but couldn't be parsed"); return Err("Internal Error (See logs for details)".into()); @@ -69,6 +75,7 @@ impl<'a> CommandDispatcher<'a> { fn try_is_fitting_path( src: &mut CommandSender, + server: &mut Server, path: Vec, tree: &CommandTree, mut raw_args: RawArgs, @@ -79,7 +86,7 @@ impl<'a> CommandDispatcher<'a> { match node.node_type { NodeType::ExecuteLeaf { run } => { return if raw_args.is_empty() { - run(src, &parsed_args)?; + run(src, server, &parsed_args)?; Ok(true) } else { Ok(false) diff --git a/pumpkin/src/commands/mod.rs b/pumpkin/src/commands/mod.rs index a827303ce..1321ec665 100644 --- a/pumpkin/src/commands/mod.rs +++ b/pumpkin/src/commands/mod.rs @@ -4,6 +4,7 @@ use std::sync::OnceLock; use crate::commands::dispatcher::CommandDispatcher; use crate::entity::player::Player; +use crate::server::Server; mod arg_player; mod cmd_gamemode; mod cmd_help; @@ -83,10 +84,10 @@ fn dispatcher_init<'a>() -> CommandDispatcher<'a> { dispatcher } -pub fn handle_command(sender: &mut CommandSender, cmd: &str) { +pub fn handle_command(sender: &mut CommandSender, server: &mut Server, cmd: &str) { let dispatcher = DISPATCHER.get_or_init(dispatcher_init); - if let Err(err) = dispatcher.dispatch(sender, cmd) { + if let Err(err) = dispatcher.dispatch(sender, server, cmd) { sender.send_message( TextComponent::text(&err).color_named(pumpkin_core::text::color::NamedColor::Red), ) diff --git a/pumpkin/src/commands/tree.rs b/pumpkin/src/commands/tree.rs index 59d2473c8..eb0647826 100644 --- a/pumpkin/src/commands/tree.rs +++ b/pumpkin/src/commands/tree.rs @@ -2,6 +2,7 @@ use std::collections::{HashMap, VecDeque}; use crate::commands::dispatcher::InvalidTreeError; use crate::commands::CommandSender; +use crate::server::Server; /// see [crate::commands::tree_builder::argument] pub(crate) type RawArgs<'a> = Vec<&'a str>; @@ -19,7 +20,8 @@ pub(crate) struct Node<'a> { pub(crate) enum NodeType<'a> { ExecuteLeaf { - run: &'a (dyn Fn(&mut CommandSender, &ConsumedArgs) -> Result<(), InvalidTreeError> + Sync), + run: &'a (dyn Fn(&mut CommandSender, &mut Server, &ConsumedArgs) -> Result<(), InvalidTreeError> + + Sync), }, #[allow(dead_code)] // todo: remove (so far no commands requiring this are implemented) Literal { string: &'a str }, diff --git a/pumpkin/src/commands/tree_builder.rs b/pumpkin/src/commands/tree_builder.rs index d34ee3a6a..338dc5f69 100644 --- a/pumpkin/src/commands/tree_builder.rs +++ b/pumpkin/src/commands/tree_builder.rs @@ -1,6 +1,7 @@ use crate::commands::dispatcher::InvalidTreeError; use crate::commands::tree::{ArgumentConsumer, CommandTree, ConsumedArgs, Node, NodeType}; use crate::commands::CommandSender; +use crate::server::Server; impl<'a> CommandTree<'a> { /// Add a child [Node] to the root of this [CommandTree]. @@ -41,7 +42,8 @@ impl<'a> CommandTree<'a> { /// Also see [NonLeafNodeBuilder::execute]. pub fn execute( mut self, - run: &'a (dyn Fn(&mut CommandSender, &ConsumedArgs) -> Result<(), InvalidTreeError> + Sync), + run: &'a (dyn Fn(&mut CommandSender, &mut Server, &ConsumedArgs) -> Result<(), InvalidTreeError> + + Sync), ) -> Self { let node = Node { node_type: NodeType::ExecuteLeaf { run }, @@ -117,7 +119,8 @@ impl<'a> NonLeafNodeBuilder<'a> { /// Also see [CommandTree::execute]. pub fn execute( mut self, - run: &'a (dyn Fn(&mut CommandSender, &ConsumedArgs) -> Result<(), InvalidTreeError> + Sync), + run: &'a (dyn Fn(&mut CommandSender, &mut Server, &ConsumedArgs) -> Result<(), InvalidTreeError> + + Sync), ) -> Self { self.leaf_nodes.push(LeafNodeBuilder { node_type: NodeType::ExecuteLeaf { run }, diff --git a/pumpkin/src/entity/player.rs b/pumpkin/src/entity/player.rs index 9925278ee..d7d1b20bf 100644 --- a/pumpkin/src/entity/player.rs +++ b/pumpkin/src/entity/player.rs @@ -7,7 +7,10 @@ use pumpkin_entity::{entity_type::EntityType, Entity, EntityId}; use pumpkin_inventory::player::PlayerInventory; use pumpkin_protocol::{ bytebuf::{packet_id::Packet, DeserializerError}, - client::play::{CGameEvent, CPlayDisconnect, CSyncPlayerPosition, CSystemChatMessage}, + client::play::{ + CGameEvent, CPlayDisconnect, CPlayerInfoUpdate, CSyncPlayerPosition, CSystemChatMessage, + PlayerAction, + }, server::play::{ SChatCommand, SChatMessage, SClientInformationPlay, SConfirmTeleport, SInteract, SPlayPingRequest, SPlayerAction, SPlayerCommand, SPlayerPosition, SPlayerPositionRotation, @@ -139,8 +142,18 @@ impl Player { self.food_saturation = food_saturation; } - pub fn set_gamemode(&mut self, gamemode: GameMode) { + pub fn set_gamemode(&mut self, server: &mut Server, gamemode: GameMode) { self.gamemode = gamemode; + server.broadcast_packet( + self, + &CPlayerInfoUpdate::new( + 0x04, + &[pumpkin_protocol::client::play::Player { + uuid: self.client.gameprofile.as_ref().unwrap().id, + actions: vec![PlayerAction::UpdateGameMode((self.gamemode as i32).into())], + }], + ), + ); self.client .send_packet(&CGameEvent::new(3, gamemode.to_f32().unwrap())); } diff --git a/pumpkin/src/main.rs b/pumpkin/src/main.rs index 3d0f2b368..e95946e6b 100644 --- a/pumpkin/src/main.rs +++ b/pumpkin/src/main.rs @@ -31,6 +31,8 @@ static ALLOC: dhat::Alloc = dhat::Alloc; #[cfg(not(target_os = "wasi"))] fn main() -> io::Result<()> { + use std::{borrow::BorrowMut, sync::{Arc, Mutex}}; + use entity::player::Player; use pumpkin_core::text::{color::NamedColor, TextComponent}; @@ -95,12 +97,16 @@ fn main() -> io::Result<()> { let rcon = advanced_configuration.rcon.clone(); let mut clients: HashMap = HashMap::new(); - let mut players: HashMap, Rc>> = HashMap::new(); + let mut players: HashMap, Arc>> = HashMap::new(); - let mut server = Server::new((basic_config, advanced_configuration)); + let mut server = Arc::new(Mutex::new(Server::new(( + basic_config, + advanced_configuration, + )))); log::info!("Started Server took {}ms", time.elapsed().as_millis()); log::info!("You now can connect to the server, Listening on {}", addr); + let server1 = server.clone(); if use_console { thread::spawn(move || { let stdin = std::io::stdin(); @@ -111,15 +117,17 @@ fn main() -> io::Result<()> { .expect("Failed to read console line"); if !out.is_empty() { - handle_command(&mut commands::CommandSender::Console, &out); + let mut server = server1.lock().unwrap(); + handle_command(&mut commands::CommandSender::Console, &mut server, &out); } } }); } if rcon.enabled { - tokio::spawn(async move { - RCONServer::new(&rcon).await.unwrap(); - }); + let server = server.clone(); + // tokio::spawn(async move { + // RCONServer::new(&rcon, &server).await.unwrap(); + // }); } loop { if let Err(err) = poll.poll(&mut events, None) { @@ -161,16 +169,17 @@ fn main() -> io::Result<()> { token, Interest::READABLE.add(Interest::WRITABLE), )?; - let rc_token = Rc::new(token); - let client = Client::new(Rc::clone(&rc_token), connection, addr); + let rc_token = Arc::new(token); + let client = Client::new(Arc::clone(&rc_token), connection, addr); clients.insert(token, client); }, token => { // Poll Players let done = if let Some(player) = players.get_mut(&token) { - let mut player = player.borrow_mut(); + let mut player = player.lock().unwrap(); player.client.poll(event).await; + let mut server = server.lock().unwrap(); player.process_packets(&mut server); player.client.closed } else { @@ -179,8 +188,9 @@ fn main() -> io::Result<()> { if done { if let Some(player) = players.remove(&token) { + let mut server = server.lock().unwrap(); server.remove_player(&token); - let mut player = player.borrow_mut(); + let mut player = player.lock().unwrap(); poll.registry().deregister(&mut player.client.connection)?; } } @@ -189,6 +199,7 @@ fn main() -> io::Result<()> { // Maybe received an event for a TCP connection. let (done, make_player) = if let Some(client) = clients.get_mut(&token) { client.poll(event).await; + let mut server = server.lock().unwrap(); client.process_packets(&mut server).await; (client.closed, client.make_player) } else { @@ -201,9 +212,10 @@ fn main() -> io::Result<()> { poll.registry().deregister(&mut client.connection)?; } else if make_player { let token = client.token.clone(); + let mut server = server.lock().unwrap(); let player = server.add_player(token.clone(), client); players.insert(token, player.clone()); - let mut player = player.borrow_mut(); + let mut player = player.lock().unwrap(); server.spawn_player(&mut player).await; } } diff --git a/pumpkin/src/rcon/mod.rs b/pumpkin/src/rcon/mod.rs index c3606ca2e..28f0a486d 100644 --- a/pumpkin/src/rcon/mod.rs +++ b/pumpkin/src/rcon/mod.rs @@ -1,6 +1,7 @@ use std::{ collections::HashMap, io::{self, Read}, + sync::{Arc, Mutex}, }; use mio::{ @@ -10,7 +11,7 @@ use mio::{ use packet::{Packet, PacketError, PacketType}; use thiserror::Error; -use crate::{commands::handle_command, config::RCONConfig}; +use crate::{commands::handle_command, config::RCONConfig, server::Server}; mod packet; @@ -29,7 +30,7 @@ const SERVER: Token = Token(0); pub struct RCONServer {} impl RCONServer { - pub async fn new(config: &RCONConfig) -> Result { + pub async fn new(config: &RCONConfig, server: &Arc>) -> Result { assert!(config.enabled, "RCON is not enabled"); let addr = format!("{}:{}", config.ip, config.port) .parse() @@ -87,7 +88,7 @@ impl RCONServer { token => { let done = if let Some(client) = connections.get_mut(&token) { - client.handle(&password).await + client.handle(&server, &password).await } else { false }; @@ -126,7 +127,7 @@ impl RCONClient { } } - pub async fn handle(&mut self, password: &str) -> bool { + pub async fn handle(&mut self, server: &Arc>, password: &str) -> bool { if !self.closed { loop { match self.read_bytes() { @@ -141,7 +142,7 @@ impl RCONClient { } } // If we get a close here, we might have a reply, which we still want to write. - match self.poll(password).await { + match self.poll(server, password).await { Ok(()) => {} Err(e) => { log::error!("rcon error: {e}"); @@ -152,7 +153,11 @@ impl RCONClient { self.closed } - async fn poll(&mut self, password: &str) -> Result<(), PacketError> { + async fn poll( + &mut self, + server: &Arc>, + password: &str, + ) -> Result<(), PacketError> { loop { let packet = match self.receive_packet().await? { Some(p) => p, @@ -183,8 +188,10 @@ impl RCONClient { PacketType::ExecCommand => { if self.logged_in { let mut output = Vec::new(); + let mut server = server.lock().unwrap(); handle_command( &mut crate::commands::CommandSender::Rcon(&mut output), + &mut server, packet.get_body(), ); for line in output { diff --git a/pumpkin/src/server.rs b/pumpkin/src/server.rs index 725f6091e..f50af89d6 100644 --- a/pumpkin/src/server.rs +++ b/pumpkin/src/server.rs @@ -6,7 +6,7 @@ use std::{ rc::Rc, sync::{ atomic::{AtomicI32, Ordering}, - Arc, + Arc, Mutex, MutexGuard, }, time::Duration, }; @@ -33,7 +33,7 @@ use pumpkin_world::{dimension::Dimension, radial_chunk_iterator::RadialIterator, use pumpkin_registry::Registry; use rsa::{traits::PublicKeyParts, RsaPrivateKey, RsaPublicKey}; use serde::{Deserialize, Serialize}; -use tokio::sync::{mpsc, Mutex}; +use tokio::sync::mpsc; use crate::{ client::Client, @@ -48,7 +48,7 @@ pub struct Server { pub private_key: RsaPrivateKey, pub public_key_der: Box<[u8]>, - pub world: Arc>, + pub world: Arc>, pub status_response: StatusResponse, // We cache the json response here so we don't parse it every time someone makes a Status request. // Keep in mind that we must parse this again, when the StatusResponse changes which usally happen when a player joins or leaves @@ -60,7 +60,7 @@ pub struct Server { /// Cache the registry so we don't have to parse it every time a player joins pub cached_registry: Vec, - pub current_players: HashMap, Rc>>, + pub current_players: HashMap, Arc>>, // TODO: replace with HashMap entity_id: AtomicI32, // TODO: place this into every world @@ -108,7 +108,7 @@ impl Server { cached_registry: Registry::get_static(), // 0 is invalid entity_id: 2.into(), - world: Arc::new(Mutex::new(world)), + world: Arc::new(tokio::sync::Mutex::new(world)), public_key, cached_server_brand, private_key, @@ -122,20 +122,20 @@ impl Server { } } - pub fn add_player(&mut self, token: Rc, client: Client) -> Rc> { + pub fn add_player(&mut self, token: Arc, client: Client) -> Arc> { let entity_id = self.new_entity_id(); let gamemode = match self.base_config.default_gamemode { GameMode::Undefined => GameMode::Survival, game_mode => game_mode, }; - let player = Rc::new(RefCell::new(Player::new(client, entity_id, gamemode))); + let player = Arc::new(Mutex::new(Player::new(client, entity_id, gamemode))); self.current_players.insert(token, player.clone()); player } pub fn remove_player(&mut self, token: &Token) { let player = self.current_players.remove(token).unwrap(); - let player = player.as_ref().borrow(); + let player = player.as_ref().lock().unwrap(); // despawn the player // todo: put this into the entitiy struct let id = player.entity_id(); @@ -204,7 +204,7 @@ impl Server { name: gameprofile.name.clone(), properties: gameprofile.properties.clone(), }, - PlayerAction::UpdateListed { listed: true }, + PlayerAction::UpdateListed(true), ], }], ), @@ -217,7 +217,7 @@ impl Server { .iter() .filter(|c| c.0 != &player.client.token) { - let playerr = playerr.as_ref().borrow(); + let playerr = playerr.as_ref().lock().unwrap(); let gameprofile = &playerr.client.gameprofile.as_ref().unwrap(); entries.push(pumpkin_protocol::client::play::Player { uuid: gameprofile.id, @@ -226,7 +226,7 @@ impl Server { name: gameprofile.name.clone(), properties: gameprofile.properties.clone(), }, - PlayerAction::UpdateListed { listed: true }, + PlayerAction::UpdateListed(true), ], }) } @@ -262,7 +262,7 @@ impl Server { // spawn players for our client let token = player.client.token.clone(); for (_, existing_player) in self.current_players.iter().filter(|c| c.0 != &token) { - let existing_player = existing_player.as_ref().borrow(); + let existing_player = existing_player.as_ref().lock().unwrap(); let entity = &existing_player.entity; let gameprofile = existing_player.client.gameprofile.as_ref().unwrap(); player.client.send_packet(&CSpawnEntity::new( @@ -297,13 +297,13 @@ impl Server { } /// TODO: This definitly should be in world - pub fn get_by_entityid(&self, from: &Player, id: EntityId) -> Option> { + pub fn get_by_entityid(&self, from: &Player, id: EntityId) -> Option> { for (_, player) in self .current_players .iter() .filter(|c| c.0 != &from.client.token) { - let player = player.borrow_mut(); + let player = player.lock().unwrap(); if player.entity_id() == id { return Some(player); } @@ -323,7 +323,7 @@ impl Server { .iter() .filter(|c| c.0 != &from.client.token) { - let mut player = player.borrow_mut(); + let mut player = player.lock().unwrap(); player.client.send_packet(packet); } } @@ -338,7 +338,7 @@ impl Server { .iter() .filter(|c| !from.contains(&c.0.as_ref())) { - let mut player = player.borrow_mut(); + let mut player = player.lock().unwrap(); player.client.send_packet(packet); } } From 8cff0b4b76fa8ff402e8f0437691413a881866df Mon Sep 17 00:00:00 2001 From: Snowiiii Date: Sun, 25 Aug 2024 13:21:24 +0200 Subject: [PATCH 7/8] Fix: clippy and fmt --- pumpkin/src/client/mod.rs | 1 - pumpkin/src/main.rs | 10 +++++----- pumpkin/src/rcon/mod.rs | 2 +- pumpkin/src/server.rs | 2 -- 4 files changed, 6 insertions(+), 9 deletions(-) diff --git a/pumpkin/src/client/mod.rs b/pumpkin/src/client/mod.rs index 5e7e01224..913019b90 100644 --- a/pumpkin/src/client/mod.rs +++ b/pumpkin/src/client/mod.rs @@ -1,7 +1,6 @@ use std::{ io::{self, Write}, net::SocketAddr, - rc::Rc, sync::Arc, }; diff --git a/pumpkin/src/main.rs b/pumpkin/src/main.rs index e95946e6b..9e7429004 100644 --- a/pumpkin/src/main.rs +++ b/pumpkin/src/main.rs @@ -8,7 +8,7 @@ use client::Client; use commands::handle_command; use config::AdvancedConfiguration; -use std::{collections::HashMap, rc::Rc, thread}; +use std::{collections::HashMap, thread}; use client::interrupted; use config::BasicConfiguration; @@ -31,7 +31,7 @@ static ALLOC: dhat::Alloc = dhat::Alloc; #[cfg(not(target_os = "wasi"))] fn main() -> io::Result<()> { - use std::{borrow::BorrowMut, sync::{Arc, Mutex}}; + use std::sync::{Arc, Mutex}; use entity::player::Player; use pumpkin_core::text::{color::NamedColor, TextComponent}; @@ -59,9 +59,9 @@ fn main() -> io::Result<()> { rayon::ThreadPoolBuilder::new().build_global().unwrap(); rt.block_on(async { const SERVER: Token = Token(0); - use std::{cell::RefCell, time::Instant}; + use std::time::Instant; - use rcon::RCONServer; + let time = Instant::now(); let basic_config = BasicConfiguration::load("configuration.toml"); @@ -99,7 +99,7 @@ fn main() -> io::Result<()> { let mut clients: HashMap = HashMap::new(); let mut players: HashMap, Arc>> = HashMap::new(); - let mut server = Arc::new(Mutex::new(Server::new(( + let server = Arc::new(Mutex::new(Server::new(( basic_config, advanced_configuration, )))); diff --git a/pumpkin/src/rcon/mod.rs b/pumpkin/src/rcon/mod.rs index 28f0a486d..d325a6702 100644 --- a/pumpkin/src/rcon/mod.rs +++ b/pumpkin/src/rcon/mod.rs @@ -88,7 +88,7 @@ impl RCONServer { token => { let done = if let Some(client) = connections.get_mut(&token) { - client.handle(&server, &password).await + client.handle(server, &password).await } else { false }; diff --git a/pumpkin/src/server.rs b/pumpkin/src/server.rs index f50af89d6..a33d212a7 100644 --- a/pumpkin/src/server.rs +++ b/pumpkin/src/server.rs @@ -1,9 +1,7 @@ use std::{ - cell::{RefCell, RefMut}, collections::HashMap, io::Cursor, path::Path, - rc::Rc, sync::{ atomic::{AtomicI32, Ordering}, Arc, Mutex, MutexGuard, From 268fc19b7bb9e43cf6967dd724f0a7454ccf483a Mon Sep 17 00:00:00 2001 From: Snowiiii Date: Sun, 25 Aug 2024 14:07:49 +0200 Subject: [PATCH 8/8] Re-enable RCON --- pumpkin/src/main.rs | 26 +++++++++++++------------- pumpkin/src/rcon/mod.rs | 21 ++++++++++++++------- 2 files changed, 27 insertions(+), 20 deletions(-) diff --git a/pumpkin/src/main.rs b/pumpkin/src/main.rs index 9e7429004..ada10f41b 100644 --- a/pumpkin/src/main.rs +++ b/pumpkin/src/main.rs @@ -1,4 +1,5 @@ #![allow(clippy::await_holding_refcell_ref)] +#![allow(clippy::await_holding_lock)] use mio::net::TcpListener; use mio::{Events, Interest, Poll, Token}; @@ -8,7 +9,7 @@ use client::Client; use commands::handle_command; use config::AdvancedConfiguration; -use std::{collections::HashMap, thread}; +use std::collections::HashMap; use client::interrupted; use config::BasicConfiguration; @@ -35,6 +36,7 @@ fn main() -> io::Result<()> { use entity::player::Player; use pumpkin_core::text::{color::NamedColor, TextComponent}; + use rcon::RCONServer; #[cfg(feature = "dhat-heap")] let _profiler = dhat::Profiler::new_heap(); @@ -61,8 +63,6 @@ fn main() -> io::Result<()> { const SERVER: Token = Token(0); use std::time::Instant; - - let time = Instant::now(); let basic_config = BasicConfiguration::load("configuration.toml"); @@ -99,7 +99,7 @@ fn main() -> io::Result<()> { let mut clients: HashMap = HashMap::new(); let mut players: HashMap, Arc>> = HashMap::new(); - let server = Arc::new(Mutex::new(Server::new(( + let server = Arc::new(tokio::sync::Mutex::new(Server::new(( basic_config, advanced_configuration, )))); @@ -108,7 +108,7 @@ fn main() -> io::Result<()> { let server1 = server.clone(); if use_console { - thread::spawn(move || { + tokio::spawn(async move { let stdin = std::io::stdin(); loop { let mut out = String::new(); @@ -117,7 +117,7 @@ fn main() -> io::Result<()> { .expect("Failed to read console line"); if !out.is_empty() { - let mut server = server1.lock().unwrap(); + let mut server = server1.lock().await; handle_command(&mut commands::CommandSender::Console, &mut server, &out); } } @@ -125,9 +125,9 @@ fn main() -> io::Result<()> { } if rcon.enabled { let server = server.clone(); - // tokio::spawn(async move { - // RCONServer::new(&rcon, &server).await.unwrap(); - // }); + tokio::spawn(async move { + RCONServer::new(&rcon, server).await.unwrap(); + }); } loop { if let Err(err) = poll.poll(&mut events, None) { @@ -179,7 +179,7 @@ fn main() -> io::Result<()> { let done = if let Some(player) = players.get_mut(&token) { let mut player = player.lock().unwrap(); player.client.poll(event).await; - let mut server = server.lock().unwrap(); + let mut server = server.lock().await; player.process_packets(&mut server); player.client.closed } else { @@ -188,7 +188,7 @@ fn main() -> io::Result<()> { if done { if let Some(player) = players.remove(&token) { - let mut server = server.lock().unwrap(); + let mut server = server.lock().await; server.remove_player(&token); let mut player = player.lock().unwrap(); poll.registry().deregister(&mut player.client.connection)?; @@ -199,7 +199,7 @@ fn main() -> io::Result<()> { // Maybe received an event for a TCP connection. let (done, make_player) = if let Some(client) = clients.get_mut(&token) { client.poll(event).await; - let mut server = server.lock().unwrap(); + let mut server = server.lock().await; client.process_packets(&mut server).await; (client.closed, client.make_player) } else { @@ -212,7 +212,7 @@ fn main() -> io::Result<()> { poll.registry().deregister(&mut client.connection)?; } else if make_player { let token = client.token.clone(); - let mut server = server.lock().unwrap(); + let mut server = server.lock().await; let player = server.add_player(token.clone(), client); players.insert(token, player.clone()); let mut player = player.lock().unwrap(); diff --git a/pumpkin/src/rcon/mod.rs b/pumpkin/src/rcon/mod.rs index d325a6702..e6a94fdf8 100644 --- a/pumpkin/src/rcon/mod.rs +++ b/pumpkin/src/rcon/mod.rs @@ -1,7 +1,7 @@ use std::{ collections::HashMap, io::{self, Read}, - sync::{Arc, Mutex}, + sync::Arc, }; use mio::{ @@ -30,7 +30,10 @@ const SERVER: Token = Token(0); pub struct RCONServer {} impl RCONServer { - pub async fn new(config: &RCONConfig, server: &Arc>) -> Result { + pub async fn new( + config: &RCONConfig, + server: Arc>, + ) -> Result { assert!(config.enabled, "RCON is not enabled"); let addr = format!("{}:{}", config.ip, config.port) .parse() @@ -44,7 +47,7 @@ impl RCONServer { let mut unique_token = Token(SERVER.0 + 1); - let mut events = Events::with_capacity(128); + let mut events = Events::with_capacity(20); let mut connections: HashMap = HashMap::new(); @@ -88,7 +91,7 @@ impl RCONServer { token => { let done = if let Some(client) = connections.get_mut(&token) { - client.handle(server, &password).await + client.handle(&server, &password).await } else { false }; @@ -127,7 +130,11 @@ impl RCONClient { } } - pub async fn handle(&mut self, server: &Arc>, password: &str) -> bool { + pub async fn handle( + &mut self, + server: &Arc>, + password: &str, + ) -> bool { if !self.closed { loop { match self.read_bytes() { @@ -155,7 +162,7 @@ impl RCONClient { async fn poll( &mut self, - server: &Arc>, + server: &Arc>, password: &str, ) -> Result<(), PacketError> { loop { @@ -188,7 +195,7 @@ impl RCONClient { PacketType::ExecCommand => { if self.logged_in { let mut output = Vec::new(); - let mut server = server.lock().unwrap(); + let mut server = server.lock().await; handle_command( &mut crate::commands::CommandSender::Rcon(&mut output), &mut server,