diff options
Diffstat (limited to 'azalea-protocol/src/packets')
23 files changed, 430 insertions, 400 deletions
diff --git a/azalea-protocol/src/packets/game/clientbound_change_difficulty_packet.rs b/azalea-protocol/src/packets/game/clientbound_change_difficulty_packet.rs new file mode 100755 index 00000000..e12cfff3 --- /dev/null +++ b/azalea-protocol/src/packets/game/clientbound_change_difficulty_packet.rs @@ -0,0 +1,8 @@ +use azalea_core::difficulty::Difficulty; +use packet_macros::GamePacket; + +#[derive(Clone, Debug, GamePacket)] +pub struct ClientboundChangeDifficultyPacket { + pub difficulty: Difficulty, + pub locked: bool, +} diff --git a/azalea-protocol/src/packets/game/clientbound_custom_payload_packet.rs b/azalea-protocol/src/packets/game/clientbound_custom_payload_packet.rs new file mode 100755 index 00000000..134a3109 --- /dev/null +++ b/azalea-protocol/src/packets/game/clientbound_custom_payload_packet.rs @@ -0,0 +1,8 @@ +use azalea_core::resource_location::ResourceLocation; +use packet_macros::GamePacket; + +#[derive(Clone, Debug, GamePacket)] +pub struct ClientboundCustomPayloadPacket { + pub identifier: ResourceLocation, + pub data: Vec<u8>, +} diff --git a/azalea-protocol/src/packets/game/clientbound_declare_commands_packet.rs b/azalea-protocol/src/packets/game/clientbound_declare_commands_packet.rs new file mode 100755 index 00000000..1403630d --- /dev/null +++ b/azalea-protocol/src/packets/game/clientbound_declare_commands_packet.rs @@ -0,0 +1,96 @@ +use std::hash::Hash; + +use async_trait::async_trait; +use tokio::io::AsyncRead; + +use crate::mc_buf::{McBufReadable, Readable}; + +use super::GamePacket; + +#[derive(Hash, Clone, Debug)] +pub struct ClientboundDeclareCommandsPacket { + pub entries: Vec<BrigadierNodeStub>, + pub root_index: i32, +} + +impl ClientboundDeclareCommandsPacket { + pub fn get(self) -> GamePacket { + GamePacket::ClientboundDeclareCommandsPacket(self) + } + + pub fn write(&self, _buf: &mut Vec<u8>) -> Result<(), std::io::Error> { + panic!("ClientboundDeclareCommandsPacket::write not implemented") + } + + pub async fn read<T: tokio::io::AsyncRead + std::marker::Unpin + std::marker::Send>( + buf: &mut T, + ) -> Result<GamePacket, String> { + let node_count = buf.read_varint().await?; + println!("node_count: {}", node_count); + let mut nodes = Vec::with_capacity(node_count as usize); + for _ in 0..node_count { + let node = BrigadierNodeStub::read_into(buf).await?; + nodes.push(node); + } + let root_index = buf.read_varint().await?; + Ok(GamePacket::ClientboundDeclareCommandsPacket( + ClientboundDeclareCommandsPacket { + entries: nodes, + root_index, + }, + )) + } +} + +#[derive(Hash, Debug, Clone)] +pub struct BrigadierNodeStub {} + +// azalea_brigadier::tree::CommandNode +#[async_trait] +impl McBufReadable for BrigadierNodeStub { + async fn read_into<R>(buf: &mut R) -> Result<Self, String> + where + R: AsyncRead + std::marker::Unpin + std::marker::Send, + { + let flags = u8::read_into(buf).await?; + + let node_type = flags & 0x03; + let is_executable = flags & 0x04 != 0; + let has_redirect = flags & 0x08 != 0; + let has_suggestions_type = flags & 0x10 != 0; + println!("flags: {}, node_type: {}, is_executable: {}, has_redirect: {}, has_suggestions_type: {}", flags, node_type, is_executable, has_redirect, has_suggestions_type); + + let children = buf.read_int_id_list().await?; + println!("children: {:?}", children); + let redirect_node = if has_redirect { + buf.read_varint().await? + } else { + 0 + }; + println!("redirect_node: {}", redirect_node); + + if node_type == 2 { + let name = buf.read_utf().await?; + println!("name: {}", name); + + let resource_location = if has_suggestions_type { + Some(buf.read_resource_location().await?) + } else { + None + }; + println!( + "node_type=2, flags={}, name={}, resource_location={:?}", + flags, name, resource_location + ); + return Ok(BrigadierNodeStub {}); + } + if node_type == 1 { + let name = buf.read_utf().await?; + println!("node_type=1, flags={}, name={}", flags, name); + return Ok(BrigadierNodeStub {}); + } + println!("node_type={}, flags={}", node_type, flags); + Ok(BrigadierNodeStub {}) + // return Err("Unknown node type".to_string()); + } +} diff --git a/azalea-protocol/src/packets/game/clientbound_disconnect_packet.rs b/azalea-protocol/src/packets/game/clientbound_disconnect_packet.rs new file mode 100644 index 00000000..74f5f72e --- /dev/null +++ b/azalea-protocol/src/packets/game/clientbound_disconnect_packet.rs @@ -0,0 +1,9 @@ +use azalea_chat::component::Component; +use azalea_core::resource_location::ResourceLocation; +use packet_macros::GamePacket; +use serde::Deserialize; + +#[derive(Clone, Debug, GamePacket)] +pub struct ClientboundDisconnectPacket { + pub reason: Component, +} diff --git a/azalea-protocol/src/packets/game/clientbound_login_packet.rs b/azalea-protocol/src/packets/game/clientbound_login_packet.rs index 9043fa1a..57869202 100644..100755 --- a/azalea-protocol/src/packets/game/clientbound_login_packet.rs +++ b/azalea-protocol/src/packets/game/clientbound_login_packet.rs @@ -1,26 +1,8 @@ -use super::GamePacket; -use crate::mc_buf::{Readable, Writable}; use azalea_core::{game_type::GameType, resource_location::ResourceLocation}; +use packet_macros::GamePacket; -#[derive(Clone, Debug)] +#[derive(Clone, Debug, GamePacket)] pub struct ClientboundLoginPacket { - // private final int playerId; - // private final boolean hardcore; - // private final GameType gameType; - // @Nullable - // private final GameType previousGameType; - // private final Set<ResourceKey<Level>> levels; - // private final RegistryAccess.RegistryHolder registryHolder; - // private final DimensionType dimensionType; - // private final ResourceKey<Level> dimension; - // private final long seed; - // private final int maxPlayers; - // private final int chunkRadius; - // private final int simulationDistance; - // private final boolean reducedDebugInfo; - // private final boolean showDeathScreen; - // private final boolean isDebug; - // private final boolean isFlat; pub player_id: i32, pub hardcore: bool, pub game_type: GameType, @@ -30,93 +12,14 @@ pub struct ClientboundLoginPacket { pub dimension_type: azalea_nbt::Tag, pub dimension: ResourceLocation, pub seed: i64, + #[varint] pub max_players: i32, + #[varint] pub chunk_radius: i32, + #[varint] pub simulation_distance: i32, pub reduced_debug_info: bool, pub show_death_screen: bool, pub is_debug: bool, pub is_flat: bool, } - -impl ClientboundLoginPacket { - pub fn get(self) -> GamePacket { - GamePacket::ClientboundLoginPacket(self) - } - - pub fn write(&self, buf: &mut Vec<u8>) -> Result<(), std::io::Error> { - buf.write_int(self.player_id)?; - buf.write_boolean(self.hardcore)?; - buf.write_byte(self.game_type.to_id())?; - buf.write_byte(GameType::to_optional_id(&self.previous_game_type) as u8)?; - buf.write_list(&self.levels, |buf, resource_location| { - buf.write_resource_location(resource_location) - })?; - buf.write_nbt(&self.registry_holder)?; - buf.write_nbt(&self.dimension_type)?; - buf.write_resource_location(&self.dimension)?; - buf.write_long(self.seed)?; - buf.write_varint(self.max_players)?; - buf.write_varint(self.chunk_radius)?; - buf.write_varint(self.simulation_distance)?; - buf.write_boolean(self.reduced_debug_info)?; - buf.write_boolean(self.show_death_screen)?; - buf.write_boolean(self.is_debug)?; - buf.write_boolean(self.is_flat)?; - Ok(()) - } - - pub async fn read<T: tokio::io::AsyncRead + std::marker::Unpin + std::marker::Send>( - buf: &mut T, - ) -> Result<GamePacket, String> { - let player_id = buf.read_int().await?; - let hardcore = buf.read_boolean().await?; - let game_type = GameType::from_id(buf.read_byte().await?)?; - let previous_game_type = GameType::from_optional_id(buf.read_byte().await? as i8)?; - - let mut levels = Vec::new(); - let length = buf.read_varint().await?; - for _ in 0..length { - levels.push(buf.read_resource_location().await?); - } - - // println!("about to read nbt"); - // // read all the bytes into a buffer, print it, and panic - // let mut registry_holder_buf = Vec::new(); - // buf.read_to_end(&mut registry_holder_buf).await.unwrap(); - // println!("{:?}", String::from_utf8_lossy(®istry_holder_buf)); - // panic!(""); - - let registry_holder = buf.read_nbt().await?; - let dimension_type = buf.read_nbt().await?; - let dimension = buf.read_resource_location().await?; - let seed = buf.read_long().await?; - let max_players = buf.read_varint().await?; - let chunk_radius = buf.read_varint().await?; - let simulation_distance = buf.read_varint().await?; - let reduced_debug_info = buf.read_boolean().await?; - let show_death_screen = buf.read_boolean().await?; - let is_debug = buf.read_boolean().await?; - let is_flat = buf.read_boolean().await?; - - Ok(ClientboundLoginPacket { - player_id, - hardcore, - game_type, - previous_game_type, - levels, - registry_holder, - dimension_type, - dimension, - seed, - max_players, - chunk_radius, - simulation_distance, - reduced_debug_info, - show_death_screen, - is_debug, - is_flat, - } - .get()) - } -} diff --git a/azalea-protocol/src/packets/game/clientbound_player_abilities_packet.rs b/azalea-protocol/src/packets/game/clientbound_player_abilities_packet.rs new file mode 100755 index 00000000..f4f528cf --- /dev/null +++ b/azalea-protocol/src/packets/game/clientbound_player_abilities_packet.rs @@ -0,0 +1,57 @@ +// i don't know the actual name of this packet, i couldn't find it in the source code + +use crate::mc_buf::{McBufReadable, McBufWritable, Readable}; +use async_trait::async_trait; +use packet_macros::GamePacket; +use tokio::io::AsyncRead; + +#[derive(Clone, Debug, GamePacket)] +pub struct ClientboundPlayerAbilitiesPacket { + pub flags: PlayerAbilitiesFlags, + pub flying_speed: f32, + /// Used for the fov + pub walking_speed: f32, +} + +#[derive(Clone, Debug)] +pub struct PlayerAbilitiesFlags { + pub invulnerable: bool, + pub flying: bool, + pub can_fly: bool, + pub instant_break: bool, +} + +#[async_trait] +impl McBufReadable for PlayerAbilitiesFlags { + async fn read_into<R>(buf: &mut R) -> Result<Self, String> + where + R: AsyncRead + std::marker::Unpin + std::marker::Send, + { + let byte = buf.read_byte().await?; + Ok(PlayerAbilitiesFlags { + invulnerable: byte & 1 != 0, + flying: byte & 2 != 0, + can_fly: byte & 4 != 0, + instant_break: byte & 8 != 0, + }) + } +} + +impl McBufWritable for PlayerAbilitiesFlags { + fn write_into(&self, buf: &mut Vec<u8>) -> Result<(), std::io::Error> { + let mut byte = 0; + if self.invulnerable { + byte = byte | 1; + } + if self.flying { + byte = byte | 2; + } + if self.can_fly { + byte = byte | 4; + } + if self.instant_break { + byte = byte | 8; + } + u8::write_into(&byte, buf) + } +} diff --git a/azalea-protocol/src/packets/game/clientbound_set_carried_item_packet.rs b/azalea-protocol/src/packets/game/clientbound_set_carried_item_packet.rs new file mode 100755 index 00000000..4f0bf575 --- /dev/null +++ b/azalea-protocol/src/packets/game/clientbound_set_carried_item_packet.rs @@ -0,0 +1,7 @@ +use packet_macros::GamePacket; + +/// Sent to change the player's slot selection. +#[derive(Clone, Debug, GamePacket)] +pub struct ClientboundSetCarriedItemPacket { + pub slot: u8, +} diff --git a/azalea-protocol/src/packets/game/clientbound_update_tags_packet.rs b/azalea-protocol/src/packets/game/clientbound_update_tags_packet.rs new file mode 100755 index 00000000..a2f17370 --- /dev/null +++ b/azalea-protocol/src/packets/game/clientbound_update_tags_packet.rs @@ -0,0 +1,105 @@ +use std::collections::HashMap; + +use async_trait::async_trait; +use azalea_core::resource_location::ResourceLocation; +use packet_macros::GamePacket; +use tokio::io::AsyncRead; + +use crate::mc_buf::{McBufReadable, McBufWritable, Readable, Writable}; + +#[derive(Clone, Debug, GamePacket)] +pub struct ClientboundUpdateTagsPacket { + pub tags: HashMap<ResourceLocation, Vec<Tags>>, +} + +#[derive(Clone, Debug)] +pub struct Tags { + pub name: ResourceLocation, + pub elements: Vec<i32>, +} + +#[async_trait] +impl McBufReadable for HashMap<ResourceLocation, Vec<Tags>> { + async fn read_into<R>(buf: &mut R) -> Result<Self, String> + where + R: AsyncRead + std::marker::Unpin + std::marker::Send, + { + println!("reading tags!"); + let length = buf.read_varint().await? as usize; + println!("length: {}", length); + let mut data = HashMap::with_capacity(length); + for _ in 0..length { + let tag_type = buf.read_resource_location().await?; + println!("read tag type {}", tag_type); + let tags_count = buf.read_varint().await? as usize; + let mut tags_vec = Vec::with_capacity(tags_count); + for _ in 0..tags_count { + let tags = Tags::read_into(buf).await?; + tags_vec.push(tags); + } + println!("tags: {} {:?}", tag_type, tags_vec); + data.insert(tag_type, tags_vec); + } + Ok(data) + } +} + +impl McBufWritable for HashMap<ResourceLocation, Vec<Tags>> { + fn write_into(&self, buf: &mut Vec<u8>) -> Result<(), std::io::Error> { + buf.write_varint(self.len() as i32)?; + for (k, v) in self { + k.write_into(buf)?; + v.write_into(buf)?; + } + Ok(()) + } +} + +#[async_trait] +impl McBufReadable for Vec<Tags> { + async fn read_into<R>(buf: &mut R) -> Result<Self, String> + where + R: AsyncRead + std::marker::Unpin + std::marker::Send, + { + let tags_count = buf.read_varint().await? as usize; + let mut tags_vec = Vec::with_capacity(tags_count); + for _ in 0..tags_count { + let tags = Tags::read_into(buf).await?; + tags_vec.push(tags); + } + Ok(tags_vec) + } +} + +impl McBufWritable for Vec<Tags> { + fn write_into(&self, buf: &mut Vec<u8>) -> Result<(), std::io::Error> { + buf.write_varint(self.len() as i32)?; + for tag in self { + tag.write_into(buf)?; + } + Ok(()) + } +} + +#[async_trait] +impl McBufReadable for Tags { + async fn read_into<R>(buf: &mut R) -> Result<Self, String> + where + R: AsyncRead + std::marker::Unpin + std::marker::Send, + { + println!("reading tags."); + let name = buf.read_resource_location().await?; + println!("tags name: {}", name); + let elements = buf.read_int_id_list().await?; + println!("elements: {:?}", elements); + Ok(Tags { name, elements }) + } +} + +impl McBufWritable for Tags { + fn write_into(&self, buf: &mut Vec<u8>) -> Result<(), std::io::Error> { + self.name.write_into(buf)?; + buf.write_int_id_list(&self.elements)?; + Ok(()) + } +} diff --git a/azalea-protocol/src/packets/game/clientbound_update_view_distance_packet.rs b/azalea-protocol/src/packets/game/clientbound_update_view_distance_packet.rs new file mode 100755 index 00000000..8301c089 --- /dev/null +++ b/azalea-protocol/src/packets/game/clientbound_update_view_distance_packet.rs @@ -0,0 +1,9 @@ +// i don't know the actual name of this packet, i couldn't find it in the source code + +use packet_macros::GamePacket; + +#[derive(Clone, Debug, GamePacket)] +pub struct ClientboundUpdateViewDistancePacket { + #[varint] + pub view_distance: i32, +} diff --git a/azalea-protocol/src/packets/game/mod.rs b/azalea-protocol/src/packets/game/mod.rs index 00fa1d75..dde3f753 100644..100755 --- a/azalea-protocol/src/packets/game/mod.rs +++ b/azalea-protocol/src/packets/game/mod.rs @@ -1,46 +1,27 @@ +pub mod clientbound_change_difficulty_packet; +pub mod clientbound_custom_payload_packet; +pub mod clientbound_declare_commands_packet; +pub mod clientbound_disconnect_packet; pub mod clientbound_login_packet; +pub mod clientbound_player_abilities_packet; +pub mod clientbound_set_carried_item_packet; +pub mod clientbound_update_tags_packet; +pub mod clientbound_update_view_distance_packet; -use super::ProtocolPacket; -use crate::connect::PacketFlow; -use async_trait::async_trait; +use packet_macros::declare_state_packets; -#[derive(Clone, Debug)] -pub enum GamePacket -where - Self: Sized, -{ - ClientboundLoginPacket(clientbound_login_packet::ClientboundLoginPacket), -} - -#[async_trait] -impl ProtocolPacket for GamePacket { - fn id(&self) -> u32 { - match self { - GamePacket::ClientboundLoginPacket(_packet) => 0x00, - } - } - - fn write(&self, _buf: &mut Vec<u8>) {} - - /// Read a packet by its id, ConnectionProtocol, and flow - async fn read<T: tokio::io::AsyncRead + std::marker::Unpin + std::marker::Send>( - id: u32, - flow: &PacketFlow, - buf: &mut T, - ) -> Result<GamePacket, String> - where - Self: Sized, - { - Ok(match flow { - PacketFlow::ServerToClient => match id { - 0x26 => clientbound_login_packet::ClientboundLoginPacket::read(buf).await?, - - _ => return Err(format!("Unknown ServerToClient game packet id: {}", id)), - }, - PacketFlow::ClientToServer => match id { - // 0x00 => serverbound_hello_packet::ServerboundHelloPacket::read(buf).await?, - _ => return Err(format!("Unknown ClientToServer game packet id: {}", id)), - }, - }) +declare_state_packets!( + GamePacket, + Serverbound => {}, + Clientbound => { + 0x0e: clientbound_change_difficulty_packet::ClientboundChangeDifficultyPacket, + 0x12: clientbound_declare_commands_packet::ClientboundDeclareCommandsPacket, + 0x1a: clientbound_disconnect_packet::ClientboundDisconnectPacket, + 0x18: clientbound_custom_payload_packet::ClientboundCustomPayloadPacket, + 0x26: clientbound_login_packet::ClientboundLoginPacket, + 0x32: clientbound_player_abilities_packet::ClientboundPlayerAbilitiesPacket, + 0x48: clientbound_set_carried_item_packet::ClientboundSetCarriedItemPacket, + 0x4a: clientbound_update_view_distance_packet::ClientboundUpdateViewDistancePacket, + 0x67: clientbound_update_tags_packet::ClientboundUpdateTagsPacket } -} +); diff --git a/azalea-protocol/src/packets/handshake/client_intention_packet.rs b/azalea-protocol/src/packets/handshake/client_intention_packet.rs index 939a695e..a92d65f6 100644..100755 --- a/azalea-protocol/src/packets/handshake/client_intention_packet.rs +++ b/azalea-protocol/src/packets/handshake/client_intention_packet.rs @@ -1,34 +1,34 @@ -use std::hash::Hash; - use crate::{mc_buf::Writable, packets::ConnectionProtocol}; +use packet_macros::HandshakePacket; +use std::hash::Hash; use super::HandshakePacket; -#[derive(Hash, Clone, Debug)] +#[derive(Hash, Clone, Debug, HandshakePacket)] pub struct ClientIntentionPacket { + #[varint] pub protocol_version: u32, pub hostname: String, pub port: u16, - /// 1 for status, 2 for login pub intention: ConnectionProtocol, } -impl ClientIntentionPacket { - pub fn get(self) -> HandshakePacket { - HandshakePacket::ClientIntentionPacket(self) - } +// impl ClientIntentionPacket { +// pub fn get(self) -> HandshakePacket { +// HandshakePacket::ClientIntentionPacket(self) +// } - pub fn write(&self, buf: &mut Vec<u8>) { - buf.write_varint(self.protocol_version as i32).unwrap(); - buf.write_utf(&self.hostname).unwrap(); - buf.write_short(self.port).unwrap(); - buf.write_varint(self.intention.clone() as i32).unwrap(); - } +// pub fn write(&self, buf: &mut Vec<u8>) -> Result<(), std::io::Error> { +// buf.write_varint(self.protocol_version as i32)?; +// buf.write_utf(&self.hostname)?; +// buf.write_short(self.port as i16)?; +// buf.write_varint(self.intention as i32)?; +// Ok(()) +// } - pub async fn read<T: tokio::io::AsyncRead + std::marker::Unpin + std::marker::Send>( - _buf: &mut T, - ) -> Result<HandshakePacket, String> { - Err("ClientIntentionPacket::parse not implemented".to_string()) - // Ok(ClientIntentionPacket {}.get()) - } -} +// pub async fn read<T: tokio::io::AsyncRead + std::marker::Unpin + std::marker::Send>( +// buf: &mut T, +// ) -> Result<HandshakePacket, String> { +// todo!() +// } +// } diff --git a/azalea-protocol/src/packets/handshake/mod.rs b/azalea-protocol/src/packets/handshake/mod.rs index 1d753645..88d9939b 100644..100755 --- a/azalea-protocol/src/packets/handshake/mod.rs +++ b/azalea-protocol/src/packets/handshake/mod.rs @@ -1,48 +1,11 @@ pub mod client_intention_packet; -use async_trait::async_trait; +use packet_macros::declare_state_packets; -use crate::connect::PacketFlow; - -use super::ProtocolPacket; - -#[derive(Clone, Debug)] -pub enum HandshakePacket -where - Self: Sized, -{ - ClientIntentionPacket(client_intention_packet::ClientIntentionPacket), -} - -#[async_trait] -impl ProtocolPacket for HandshakePacket { - fn id(&self) -> u32 { - match self { - HandshakePacket::ClientIntentionPacket(_packet) => 0x00, - } - } - - fn write(&self, buf: &mut Vec<u8>) { - match self { - HandshakePacket::ClientIntentionPacket(packet) => packet.write(buf), - } - } - - /// Read a packet by its id, ConnectionProtocol, and flow - async fn read<T: tokio::io::AsyncRead + std::marker::Unpin + std::marker::Send>( - id: u32, - flow: &PacketFlow, - buf: &mut T, - ) -> Result<HandshakePacket, String> - where - Self: Sized, - { - match flow { - PacketFlow::ServerToClient => Err("HandshakePacket::read not implemented".to_string()), - PacketFlow::ClientToServer => match id { - 0x00 => Ok(client_intention_packet::ClientIntentionPacket::read(buf).await?), - _ => Err(format!("Unknown ClientToServer status packet id: {}", id)), - }, - } +declare_state_packets!( + HandshakePacket, + Serverbound => {}, + Clientbound => { + 0x00: client_intention_packet::ClientIntentionPacket, } -} +); diff --git a/azalea-protocol/src/packets/login/clientbound_custom_query_packet.rs b/azalea-protocol/src/packets/login/clientbound_custom_query_packet.rs index 2bc1fc1e..3138106e 100644..100755 --- a/azalea-protocol/src/packets/login/clientbound_custom_query_packet.rs +++ b/azalea-protocol/src/packets/login/clientbound_custom_query_packet.rs @@ -1,37 +1,11 @@ -use super::LoginPacket; -use crate::mc_buf::{Readable, Writable}; use azalea_core::resource_location::ResourceLocation; +use packet_macros::LoginPacket; use std::hash::Hash; -#[derive(Hash, Clone, Debug)] +#[derive(Hash, Clone, Debug, LoginPacket)] pub struct ClientboundCustomQueryPacket { + #[varint] pub transaction_id: u32, pub identifier: ResourceLocation, pub data: Vec<u8>, } - -impl ClientboundCustomQueryPacket { - pub fn get(self) -> LoginPacket { - LoginPacket::ClientboundCustomQueryPacket(self) - } - - pub fn write(&self, buf: &mut Vec<u8>) { - buf.write_varint(self.transaction_id as i32).unwrap(); - buf.write_utf(self.identifier.to_string().as_str()).unwrap(); - buf.write_bytes(&self.data).unwrap(); - } - - pub async fn read<T: tokio::io::AsyncRead + std::marker::Unpin + std::marker::Send>( - buf: &mut T, - ) -> Result<LoginPacket, String> { - let transaction_id = buf.read_varint().await? as u32; - let identifier = ResourceLocation::new(&buf.read_utf().await?)?; - let data = buf.read_bytes(1048576).await?; - Ok(ClientboundCustomQueryPacket { - transaction_id, - identifier, - data, - } - .get()) - } -} diff --git a/azalea-protocol/src/packets/login/clientbound_game_profile_packet.rs b/azalea-protocol/src/packets/login/clientbound_game_profile_packet.rs index 1a752c1a..c54aa819 100644..100755 --- a/azalea-protocol/src/packets/login/clientbound_game_profile_packet.rs +++ b/azalea-protocol/src/packets/login/clientbound_game_profile_packet.rs @@ -14,11 +14,12 @@ impl ClientboundGameProfilePacket { LoginPacket::ClientboundGameProfilePacket(self) } - pub fn write(&self, buf: &mut Vec<u8>) { + pub fn write(&self, buf: &mut Vec<u8>) -> Result<(), std::io::Error> { for n in self.game_profile.uuid.to_int_array() { buf.write_int(n as i32).unwrap(); } buf.write_utf(self.game_profile.name.as_str()).unwrap(); + Ok(()) } pub async fn read<T: tokio::io::AsyncRead + std::marker::Unpin + std::marker::Send>( diff --git a/azalea-protocol/src/packets/login/clientbound_hello_packet.rs b/azalea-protocol/src/packets/login/clientbound_hello_packet.rs index e0b865be..9d0cec39 100644..100755 --- a/azalea-protocol/src/packets/login/clientbound_hello_packet.rs +++ b/azalea-protocol/src/packets/login/clientbound_hello_packet.rs @@ -16,7 +16,7 @@ impl ClientboundHelloPacket { LoginPacket::ClientboundHelloPacket(self) } - pub fn write(&self, _buf: &mut Vec<u8>) { + pub fn write(&self, _buf: &mut Vec<u8>) -> Result<(), std::io::Error> { panic!("ClientboundHelloPacket::write not implemented") } diff --git a/azalea-protocol/src/packets/login/clientbound_login_compression_packet.rs b/azalea-protocol/src/packets/login/clientbound_login_compression_packet.rs index af355192..a88c6cbf 100644..100755 --- a/azalea-protocol/src/packets/login/clientbound_login_compression_packet.rs +++ b/azalea-protocol/src/packets/login/clientbound_login_compression_packet.rs @@ -14,8 +14,9 @@ impl ClientboundLoginCompressionPacket { LoginPacket::ClientboundLoginCompressionPacket(self) } - pub fn write(&self, buf: &mut Vec<u8>) { + pub fn write(&self, buf: &mut Vec<u8>) -> Result<(), std::io::Error> { buf.write_varint(self.compression_threshold).unwrap(); + Ok(()) } pub async fn read<T: tokio::io::AsyncRead + std::marker::Unpin + std::marker::Send>( diff --git a/azalea-protocol/src/packets/login/clientbound_login_disconnect_packet.rs b/azalea-protocol/src/packets/login/clientbound_login_disconnect_packet.rs new file mode 100644 index 00000000..28d91c79 --- /dev/null +++ b/azalea-protocol/src/packets/login/clientbound_login_disconnect_packet.rs @@ -0,0 +1,7 @@ +use azalea_chat::component::Component; +use packet_macros::LoginPacket; + +#[derive(Clone, Debug, LoginPacket)] +pub struct ClientboundLoginDisconnectPacket { + pub reason: Component, +} diff --git a/azalea-protocol/src/packets/login/mod.rs b/azalea-protocol/src/packets/login/mod.rs index 4d490d08..ab68518c 100644..100755 --- a/azalea-protocol/src/packets/login/mod.rs +++ b/azalea-protocol/src/packets/login/mod.rs @@ -2,78 +2,22 @@ pub mod clientbound_custom_query_packet; pub mod clientbound_game_profile_packet; pub mod clientbound_hello_packet; pub mod clientbound_login_compression_packet; +pub mod clientbound_login_disconnect_packet; pub mod serverbound_hello_packet; -use super::ProtocolPacket; -use crate::connect::PacketFlow; -use async_trait::async_trait; +use packet_macros::declare_state_packets; -#[derive(Clone, Debug)] -pub enum LoginPacket -where - Self: Sized, -{ - ClientboundCustomQueryPacket(clientbound_custom_query_packet::ClientboundCustomQueryPacket), - ClientboundGameProfilePacket(clientbound_game_profile_packet::ClientboundGameProfilePacket), - ClientboundHelloPacket(clientbound_hello_packet::ClientboundHelloPacket), - ClientboundLoginCompressionPacket( - clientbound_login_compression_packet::ClientboundLoginCompressionPacket, - ), - ServerboundHelloPacket(serverbound_hello_packet::ServerboundHelloPacket), -} - -#[async_trait] -impl ProtocolPacket for LoginPacket { - fn id(&self) -> u32 { - match self { - LoginPacket::ClientboundCustomQueryPacket(_packet) => 0x04, - LoginPacket::ClientboundGameProfilePacket(_packet) => 0x02, - LoginPacket::ClientboundHelloPacket(_packet) => 0x01, - LoginPacket::ClientboundLoginCompressionPacket(_packet) => 0x03, - LoginPacket::ServerboundHelloPacket(_packet) => 0x00, - } - } - - fn write(&self, buf: &mut Vec<u8>) { - match self { - LoginPacket::ClientboundCustomQueryPacket(packet) => packet.write(buf), - LoginPacket::ClientboundGameProfilePacket(packet) => packet.write(buf), - LoginPacket::ClientboundHelloPacket(packet) => packet.write(buf), - LoginPacket::ClientboundLoginCompressionPacket(packet) => packet.write(buf), - LoginPacket::ServerboundHelloPacket(packet) => packet.write(buf), - } - } - - /// Read a packet by its id, ConnectionProtocol, and flow - async fn read<T: tokio::io::AsyncRead + std::marker::Unpin + std::marker::Send>( - id: u32, - flow: &PacketFlow, - buf: &mut T, - ) -> Result<LoginPacket, String> - where - Self: Sized, - { - Ok(match flow { - PacketFlow::ServerToClient => match id { - 0x01 => clientbound_hello_packet::ClientboundHelloPacket::read(buf).await?, - 0x02 => { - clientbound_game_profile_packet::ClientboundGameProfilePacket::read(buf).await? - } - 0x04 => { - clientbound_custom_query_packet::ClientboundCustomQueryPacket::read(buf).await? - } - 0x03 => { - clientbound_login_compression_packet::ClientboundLoginCompressionPacket::read( - buf, - ) - .await? - } - _ => return Err(format!("Unknown ServerToClient login packet id: {}", id)), - }, - PacketFlow::ClientToServer => match id { - 0x00 => serverbound_hello_packet::ServerboundHelloPacket::read(buf).await?, - _ => return Err(format!("Unknown ClientToServer login packet id: {}", id)), - }, - }) +declare_state_packets!( + LoginPacket, + Serverbound => { + 0x00: serverbound_hello_packet::ServerboundHelloPacket, + }, + Clientbound => { + // 0x00: clientbound_login_disconnect_packet::ClientboundLoginDisconnectPacket, + 26: clientbound_login_disconnect_packet::ClientboundLoginDisconnectPacket, + 0x01: clientbound_hello_packet::ClientboundHelloPacket, + 0x02: clientbound_game_profile_packet::ClientboundGameProfilePacket, + 0x03: clientbound_login_compression_packet::ClientboundLoginCompressionPacket, + 0x04: clientbound_custom_query_packet::ClientboundCustomQueryPacket, } -} +); diff --git a/azalea-protocol/src/packets/login/serverbound_hello_packet.rs b/azalea-protocol/src/packets/login/serverbound_hello_packet.rs index 0039cbce..a72480f2 100644..100755 --- a/azalea-protocol/src/packets/login/serverbound_hello_packet.rs +++ b/azalea-protocol/src/packets/login/serverbound_hello_packet.rs @@ -14,8 +14,9 @@ impl ServerboundHelloPacket { LoginPacket::ServerboundHelloPacket(self) } - pub fn write(&self, buf: &mut Vec<u8>) { + pub fn write(&self, buf: &mut Vec<u8>) -> Result<(), std::io::Error> { buf.write_utf(&self.username).unwrap(); + Ok(()) } pub async fn read<T: tokio::io::AsyncRead + std::marker::Unpin + std::marker::Send>( diff --git a/azalea-protocol/src/packets/mod.rs b/azalea-protocol/src/packets/mod.rs index e065b65c..98741a75 100644..100755 --- a/azalea-protocol/src/packets/mod.rs +++ b/azalea-protocol/src/packets/mod.rs @@ -3,13 +3,18 @@ pub mod handshake; pub mod login; pub mod status; +use crate::{ + connect::PacketFlow, + mc_buf::{McBufReadable, McBufWritable, Readable, Writable}, +}; use async_trait::async_trait; +use num_derive::FromPrimitive; +use num_traits::FromPrimitive; +use tokio::io::AsyncRead; -use crate::connect::PacketFlow; +pub const PROTOCOL_VERSION: u32 = 758; -pub const PROTOCOL_VERSION: u32 = 757; - -#[derive(Debug, Clone, PartialEq, Eq, Hash)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, FromPrimitive)] pub enum ConnectionProtocol { Handshake = -1, Game = 0, @@ -42,5 +47,22 @@ where where Self: Sized; - fn write(&self, buf: &mut Vec<u8>); + fn write(&self, buf: &mut Vec<u8>) -> Result<(), std::io::Error>; +} + +#[async_trait] +impl McBufReadable for ConnectionProtocol { + async fn read_into<R>(buf: &mut R) -> Result<Self, String> + where + R: AsyncRead + std::marker::Unpin + std::marker::Send, + { + ConnectionProtocol::from_i32(buf.read_varint().await?) + .ok_or_else(|| "Invalid intention".to_string()) + } +} + +impl McBufWritable for ConnectionProtocol { + fn write_into(&self, buf: &mut Vec<u8>) -> Result<(), std::io::Error> { + buf.write_varint(*self as i32) + } } diff --git a/azalea-protocol/src/packets/status/clientbound_status_response_packet.rs b/azalea-protocol/src/packets/status/clientbound_status_response_packet.rs index 38270ad1..884cf408 100644..100755 --- a/azalea-protocol/src/packets/status/clientbound_status_response_packet.rs +++ b/azalea-protocol/src/packets/status/clientbound_status_response_packet.rs @@ -36,10 +36,12 @@ pub struct ClientboundStatusResponsePacket { impl ClientboundStatusResponsePacket { pub fn get(self) -> StatusPacket { - StatusPacket::ClientboundStatusResponsePacket(Box::new(self)) + StatusPacket::ClientboundStatusResponsePacket(self) } - pub fn write(&self, _buf: &mut Vec<u8>) {} + pub fn write(&self, _buf: &mut Vec<u8>) -> Result<(), std::io::Error> { + Ok(()) + } pub async fn read<T: tokio::io::AsyncRead + std::marker::Unpin + std::marker::Send>( buf: &mut T, diff --git a/azalea-protocol/src/packets/status/mod.rs b/azalea-protocol/src/packets/status/mod.rs index 6383bae8..56aa577e 100644..100755 --- a/azalea-protocol/src/packets/status/mod.rs +++ b/azalea-protocol/src/packets/status/mod.rs @@ -1,65 +1,14 @@ pub mod clientbound_status_response_packet; pub mod serverbound_status_request_packet; -use async_trait::async_trait; - -use crate::connect::PacketFlow; - -use super::ProtocolPacket; - -#[derive(Clone, Debug)] -pub enum StatusPacket -where - Self: Sized, -{ - ServerboundStatusRequestPacket( - serverbound_status_request_packet::ServerboundStatusRequestPacket, - ), - ClientboundStatusResponsePacket( - Box<clientbound_status_response_packet::ClientboundStatusResponsePacket>, - ), -} - -#[async_trait] -impl ProtocolPacket for StatusPacket { - fn id(&self) -> u32 { - match self { - StatusPacket::ServerboundStatusRequestPacket(_packet) => 0x00, - StatusPacket::ClientboundStatusResponsePacket(_packet) => 0x00, - } - } - - fn write(&self, buf: &mut Vec<u8>) { - match self { - StatusPacket::ServerboundStatusRequestPacket(packet) => packet.write(buf), - StatusPacket::ClientboundStatusResponsePacket(packet) => packet.write(buf), - } - } - - /// Read a packet by its id, ConnectionProtocol, and flow - async fn read<T: tokio::io::AsyncRead + std::marker::Unpin + std::marker::Send>( - id: u32, - flow: &PacketFlow, - buf: &mut T, - ) -> Result<StatusPacket, String> - where - Self: Sized, - { - match flow { - PacketFlow::ServerToClient => match id { - 0x00 => Ok( - clientbound_status_response_packet::ClientboundStatusResponsePacket::read(buf) - .await?, - ), - _ => Err(format!("Unknown ServerToClient status packet id: {}", id)), - }, - PacketFlow::ClientToServer => match id { - 0x00 => Ok( - serverbound_status_request_packet::ServerboundStatusRequestPacket::read(buf) - .await?, - ), - _ => Err(format!("Unknown ClientToServer status packet id: {}", id)), - }, - } +use packet_macros::declare_state_packets; + +declare_state_packets!( + StatusPacket, + Serverbound => { + 0x00: serverbound_status_request_packet::ServerboundStatusRequestPacket, + }, + Clientbound => { + 0x00: clientbound_status_response_packet::ClientboundStatusResponsePacket, } -} +); diff --git a/azalea-protocol/src/packets/status/serverbound_status_request_packet.rs b/azalea-protocol/src/packets/status/serverbound_status_request_packet.rs index 3a25ac42..e77687ec 100644..100755 --- a/azalea-protocol/src/packets/status/serverbound_status_request_packet.rs +++ b/azalea-protocol/src/packets/status/serverbound_status_request_packet.rs @@ -1,22 +1,5 @@ +use packet_macros::StatusPacket; use std::hash::Hash; -use super::StatusPacket; - -#[derive(Hash, Clone, Debug)] +#[derive(Clone, Debug, StatusPacket)] pub struct ServerboundStatusRequestPacket {} - -impl ServerboundStatusRequestPacket { - pub fn get(self) -> StatusPacket { - StatusPacket::ServerboundStatusRequestPacket(self) - } - - pub fn write(&self, _buf: &mut Vec<u8>) { - panic!("ServerboundStatusRequestPacket::write not implemented") - } - - pub async fn read<T: tokio::io::AsyncRead + std::marker::Unpin + std::marker::Send>( - _buf: &mut T, - ) -> Result<StatusPacket, String> { - Err("ServerboundStatusRequestPacket::read not implemented".to_string()) - } -} |
