Skip to content

Commit

Permalink
Move from ids to uuids
Browse files Browse the repository at this point in the history
  • Loading branch information
Snowiiii committed Oct 23, 2024
1 parent e396399 commit 14ff151
Show file tree
Hide file tree
Showing 9 changed files with 65 additions and 88 deletions.
40 changes: 19 additions & 21 deletions pumpkin/src/client/client_packet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use pumpkin_protocol::{
use uuid::Uuid;

use crate::{
client::authentication::{self, validate_textures, GameProfile},
client::authentication::{self, offline_uuid, validate_textures, GameProfile},
entity::player::{ChatMode, Hand},
proxy::{
bungeecord,
Expand All @@ -39,11 +39,7 @@ impl Client {
.store(version, std::sync::atomic::Ordering::Relaxed);
*self.server_address.lock().await = handshake.server_address;

log::debug!(
"Handshake: id {} is now in state {:?}",
self.id,
&handshake.next_state
);
log::debug!("Handshake: next state {:?}", &handshake.next_state);
self.connection_state.store(handshake.next_state);
if self.connection_state.load() != ConnectionState::Status {
let protocol = version;
Expand All @@ -60,13 +56,13 @@ impl Client {
}

pub async fn handle_status_request(&self, server: &Server, _status_request: SStatusRequest) {
log::debug!("Handling status request for id {}", self.id);
log::debug!("Handling status request for id");
let status = server.get_status();
self.send_packet(&status.lock().await.get_status()).await;
}

pub async fn handle_ping_request(&self, ping_request: SStatusPingRequest) {
log::debug!("Handling ping request for id {}", self.id);
log::debug!("Handling ping request for id");
self.send_packet(&CPingResponse::new(ping_request.payload))
.await;
self.close();
Expand All @@ -80,11 +76,7 @@ impl Client {
}

pub async fn handle_login_start(&self, server: &Server, login_start: SLoginStart) {
log::debug!(
"login start for id {}, State {:?}",
self.id,
self.connection_state
);
log::debug!("login start");

if !Self::is_valid_player_name(&login_start.name) {
self.kick("Invalid characters in username").await;
Expand All @@ -108,8 +100,14 @@ impl Client {
}
}
} else {
let id = if BASIC_CONFIG.online_mode {
login_start.uuid
} else {
offline_uuid(&login_start.name).expect("This is very not safe and bad")
};

let profile = GameProfile {
id: login_start.uuid,
id,
name: login_start.name,
properties: vec![],
profile_actions: None,
Expand Down Expand Up @@ -137,7 +135,7 @@ impl Client {
server: &Server,
encryption_response: SEncryptionResponse,
) {
log::debug!("Handling encryption for id {}", self.id);
log::debug!("Handling encryption for id");
let shared_secret = server.decrypt(&encryption_response.shared_secret).unwrap();

if let Err(error) = self.set_encryption(Some(&shared_secret)).await {
Expand Down Expand Up @@ -228,7 +226,7 @@ impl Client {
}

pub async fn handle_plugin_response(&self, plugin_response: SLoginPluginResponse) {
log::debug!("Handling plugin for id {}", self.id);
log::debug!("Handling plugin for id");
let velocity_config = &ADVANCED_CONFIG.proxy.velocity;
if velocity_config.enabled {
let mut address = self.address.lock().await;
Expand All @@ -252,7 +250,7 @@ impl Client {
server: &Server,
_login_acknowledged: SLoginAcknowledged,
) {
log::debug!("Handling login acknowledged for id {}", self.id);
log::debug!("Handling login acknowledged for id");
self.connection_state.store(ConnectionState::Config);
self.send_packet(&server.get_branding()).await;

Expand Down Expand Up @@ -289,7 +287,7 @@ impl Client {
&self,
client_information: SClientInformationConfig,
) {
log::debug!("Handling client settings for id {}", self.id);
log::debug!("Handling client settings for id");
if let (Some(main_hand), Some(chat_mode)) = (
Hand::from_i32(client_information.main_hand.into()),
ChatMode::from_i32(client_information.chat_mode.into()),
Expand All @@ -310,7 +308,7 @@ impl Client {
}

pub async fn handle_plugin_message(&self, plugin_message: SPluginMessage) {
log::debug!("Handling plugin message for id {}", self.id);
log::debug!("Handling plugin message for id");
if plugin_message.channel.starts_with("minecraft:brand")
|| plugin_message.channel.starts_with("MC|Brand")
{
Expand All @@ -323,7 +321,7 @@ impl Client {
}

pub async fn handle_known_packs(&self, server: &Server, _config_acknowledged: SKnownPacks) {
log::debug!("Handling known packs for id {}", self.id);
log::debug!("Handling known packs for id");
for registry in &server.cached_registry {
self.send_packet(&CRegistryData::new(
&registry.registry_id,
Expand All @@ -338,7 +336,7 @@ impl Client {
}

pub fn handle_config_acknowledged(&self, _config_acknowledged: &SAcknowledgeFinishConfig) {
log::debug!("Handling config acknowledge for id {}", self.id);
log::debug!("Handling config acknowledge for id");
self.connection_state.store(ConnectionState::Play);
self.make_player
.store(true, std::sync::atomic::Ordering::Relaxed);
Expand Down
2 changes: 1 addition & 1 deletion pumpkin/src/client/container.rs
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,7 @@ impl Player {
.filter(|player_id| *player_id != self.entity_id())
.collect_vec()
};
let player_token = self.client.id;
let player_token = self.gameprofile.id;

// TODO: Figure out better way to get only the players from player_ids
// Also refactor out a better method to get individual advanced state ids
Expand Down
27 changes: 8 additions & 19 deletions pumpkin/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,6 @@ pub struct Client {
pub encryption: AtomicBool,
/// Indicates if the client connection is closed.
pub closed: AtomicBool,
/// A unique id identifying the client.
pub id: usize,
/// The underlying TCP connection to the client.
pub connection_reader: Arc<Mutex<tokio::net::tcp::OwnedReadHalf>>,
pub connection_writer: Arc<Mutex<tokio::net::tcp::OwnedWriteHalf>>,
Expand All @@ -126,15 +124,14 @@ pub struct Client {

impl Client {
#[must_use]
pub fn new(id: usize, connection: tokio::net::TcpStream, address: SocketAddr) -> Self {
pub fn new(connection: tokio::net::TcpStream, address: SocketAddr) -> Self {
let (connection_reader, connection_writer) = connection.into_split();
Self {
protocol_version: AtomicI32::new(0),
gameprofile: Mutex::new(None),
config: Mutex::new(None),
brand: Mutex::new(None),
server_address: Mutex::new(String::new()),
id,
address: Mutex::new(address),
connection_state: AtomicCell::new(ConnectionState::HandShake),
connection_reader: Arc::new(Mutex::new(connection_reader)),
Expand Down Expand Up @@ -198,11 +195,7 @@ impl Client {
{
self.kick(&error.to_string()).await;
} else if let Err(error) = writer.flush().await {
log::warn!(
"Failed to flush writer for id {}: {}",
self.id,
error.to_string()
);
log::warn!("Failed to flush writer for: {}", error.to_string());
}
}

Expand Down Expand Up @@ -280,7 +273,7 @@ impl Client {
&self,
packet: &mut RawPacket,
) -> Result<(), DeserializerError> {
log::debug!("Handling handshake group for id {}", self.id);
log::debug!("Handling handshake group");
let bytebuf = &mut packet.bytebuf;
match packet.id.0 {
0 => {
Expand All @@ -301,7 +294,7 @@ impl Client {
server: &Arc<Server>,
packet: &mut RawPacket,
) -> Result<(), DeserializerError> {
log::debug!("Handling status group for id {}", self.id);
log::debug!("Handling status group");
let bytebuf = &mut packet.bytebuf;
if let Some(packet) = ServerboundStatusPackets::from_i32(packet.id.0) {
match packet {
Expand Down Expand Up @@ -329,7 +322,7 @@ impl Client {
server: &Arc<Server>,
packet: &mut RawPacket,
) -> Result<(), DeserializerError> {
log::debug!("Handling login group for id {}", self.id);
log::debug!("Handling login group for id");
let bytebuf = &mut packet.bytebuf;
if let Some(packet) = ServerboundLoginPackets::from_i32(packet.id.0) {
match packet {
Expand Down Expand Up @@ -366,7 +359,7 @@ impl Client {
server: &Arc<Server>,
packet: &mut RawPacket,
) -> Result<(), DeserializerError> {
log::debug!("Handling config group for id {}", self.id);
log::debug!("Handling config group");
let bytebuf = &mut packet.bytebuf;
if let Some(packet) = ServerboundConfigPackets::from_i32(packet.id.0) {
#[expect(clippy::match_same_arms)]
Expand Down Expand Up @@ -414,11 +407,7 @@ impl Client {
return true;
}
Ok(None) => (), //log::debug!("Waiting for more data to complete packet..."),
Err(err) => log::warn!(
"Failed to decode packet for id {}: {}",
self.id,
err.to_string()
),
Err(err) => log::warn!("Failed to decode packet for: {}", err.to_string()),
}

dec.reserve(4096);
Expand Down Expand Up @@ -448,7 +437,7 @@ impl Client {

/// Kicks the Client with a reason depending on the connection state
pub async fn kick(&self, reason: &str) {
log::info!("Kicking Client id {} for {}", self.id, reason);
log::info!("Kicking Client for {}", reason);
match self.connection_state.load() {
ConnectionState::Login => {
self.try_send_packet(&CLoginDisconnect::new(
Expand Down
12 changes: 6 additions & 6 deletions pumpkin/src/client/player_packet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ impl Player {
// send new position to all other players
world
.broadcast_packet_expect(
&[self.client.id],
&[self.gameprofile.id],
&CUpdateEntityPos::new(
entity_id.into(),
x.mul_add(4096.0, -(last_x * 4096.0)) as i16,
Expand Down Expand Up @@ -186,7 +186,7 @@ impl Player {

world
.broadcast_packet_expect(
&[self.client.id],
&[self.gameprofile.id],
&CUpdateEntityPosRot::new(
entity_id.into(),
x.mul_add(4096.0, -(last_x * 4096.0)) as i16,
Expand All @@ -200,7 +200,7 @@ impl Player {
.await;
world
.broadcast_packet_expect(
&[self.client.id],
&[self.gameprofile.id],
&CHeadRot::new(entity_id.into(), yaw as u8),
)
.await;
Expand Down Expand Up @@ -230,11 +230,11 @@ impl Player {
let packet =
CUpdateEntityRot::new(entity_id.into(), yaw as u8, pitch as u8, rotation.ground);
world
.broadcast_packet_expect(&[self.client.id], &packet)
.broadcast_packet_expect(&[self.gameprofile.id], &packet)
.await;
let packet = CHeadRot::new(entity_id.into(), yaw as u8);
world
.broadcast_packet_expect(&[self.client.id], &packet)
.broadcast_packet_expect(&[self.gameprofile.id], &packet)
.await;
}

Expand Down Expand Up @@ -325,7 +325,7 @@ impl Player {
let world = &self.living_entity.entity.world;
world
.broadcast_packet_expect(
&[self.client.id],
&[self.gameprofile.id],
&CEntityAnimation::new(id.into(), animation as u8),
)
.await;
Expand Down
4 changes: 2 additions & 2 deletions pumpkin/src/entity/player.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ impl Player {

log::debug!(
"Removing player id {}, unwatching {} chunks",
self.client.id,
self.gameprofile.name,
all_chunks.len()
);
self.living_entity
Expand All @@ -168,7 +168,7 @@ impl Player {

log::debug!(
"Removed player id {} ({} chunks remain cached)",
self.client.id,
self.gameprofile.name,
self.living_entity.entity.world.get_cached_chunk_len().await
);
}
Expand Down
14 changes: 3 additions & 11 deletions pumpkin/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,6 @@ async fn main() -> io::Result<()> {
ticker.run(&server).await;
});
}
let mut player_count = 0;
loop {
// Asynchronously wait for an inbound socket.
let (connection, address) = listener.accept().await?;
Expand All @@ -180,16 +179,12 @@ async fn main() -> io::Result<()> {
log::warn!("failed to set TCP_NODELAY {e}");
}

player_count += 1;
let id = player_count;

log::info!(
"Accepted connection from: {} (id: {})",
"Accepted connection from: {} ",
scrub_address(&format!("{address}")),
id
);

let client = Arc::new(Client::new(id, connection, addr));
let client = Arc::new(Client::new(connection, addr));

let server = server.clone();
tokio::spawn(async move {
Expand All @@ -207,9 +202,7 @@ async fn main() -> io::Result<()> {
.make_player
.load(std::sync::atomic::Ordering::Relaxed)
{
let id = client.id;
log::debug!("Creating player for id {}", id);
let (player, world) = server.add_player(id, client).await;
let (player, world) = server.add_player(client).await;
world.spawn_player(&BASIC_CONFIG, player.clone()).await;
// poll Player
while !player
Expand All @@ -226,6 +219,5 @@ async fn main() -> io::Result<()> {
server.remove_player().await;
}
});
player_count -= 1;
}
}
6 changes: 4 additions & 2 deletions pumpkin/src/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ impl Server {
}
}

pub async fn add_player(&self, id: usize, client: Arc<Client>) -> (Arc<Player>, Arc<World>) {
pub async fn add_player(&self, client: Arc<Client>) -> (Arc<Player>, Arc<World>) {
let entity_id = self.new_entity_id();
let gamemode = match BASIC_CONFIG.default_gamemode {
GameMode::Undefined => GameMode::Survival,
Expand All @@ -104,7 +104,9 @@ impl Server {
let world = &self.worlds[0];

let player = Arc::new(Player::new(client, world.clone(), entity_id, gamemode).await);
world.add_player(id, player.clone()).await;
world
.add_player(player.gameprofile.id, player.clone())
.await;
// TODO: Config if we want increase online
if let Some(config) = player.client.config.lock().await.as_ref() {
// TODO: Config so we can also just ignore this hehe
Expand Down
Loading

0 comments on commit 14ff151

Please sign in to comment.