diff options
| author | mat <27899617+mat-1@users.noreply.github.com> | 2022-10-07 20:12:36 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-10-07 20:12:36 -0500 |
| commit | bc3aa9467ae1e2d0ea1727093af9b0af14965e69 (patch) | |
| tree | 8db3b735daed484507129eb0683db88ddec14210 /azalea-protocol | |
| parent | 695efef66fdf1e08f0cb6d8783c085875100fa2d (diff) | |
| download | azalea-drasl-bc3aa9467ae1e2d0ea1727093af9b0af14965e69.tar.xz | |
Replace impl Read with Cursor<&[u8]> (#26)
* Start getting rid of Cursor
* try to make the tests pass and fail
* make the tests pass
* remove unused uses
* fix clippy warnings
* fix potential OOM exploits
* fix OOM in az-nbt
* fix nbt benchmark
* fix a test
* start replacing it with Cursor<Vec<u8>>
* wip
* fix all the issues
* fix all tests
* fix nbt benchmark
* fix warnings
Diffstat (limited to 'azalea-protocol')
38 files changed, 199 insertions, 152 deletions
diff --git a/azalea-protocol/azalea-protocol-macros/src/lib.rs b/azalea-protocol/azalea-protocol-macros/src/lib.rs index ecdabbca..b7e85435 100644 --- a/azalea-protocol/azalea-protocol-macros/src/lib.rs +++ b/azalea-protocol/azalea-protocol-macros/src/lib.rs @@ -30,7 +30,7 @@ fn as_packet_derive(input: TokenStream, state: proc_macro2::TokenStream) -> Toke } pub fn read( - buf: &mut impl std::io::Read, + buf: &mut std::io::Cursor<&[u8]>, ) -> Result<#state, azalea_buf::BufReadError> { use azalea_buf::McBufReadable; Ok(Self::read_from(buf)?.get()) @@ -223,7 +223,7 @@ pub fn declare_state_packets(input: TokenStream) -> TokenStream { #id => { let data = #module::#name::read(buf).map_err(|e| crate::read::ReadPacketError::Parse { source: e, packet_id: #id, packet_name: #name_litstr.to_string() })?; let mut leftover = Vec::new(); - let _ = buf.read_to_end(&mut leftover); + let _ = std::io::Read::read_to_end(buf, &mut leftover); if !leftover.is_empty() { return Err(crate::read::ReadPacketError::LeftoverData { packet_name: #name_litstr.to_string(), data: leftover }); } @@ -250,9 +250,10 @@ pub fn declare_state_packets(input: TokenStream) -> TokenStream { #[cfg(debug_assertions)] { let mut leftover = Vec::new(); - let _ = buf.read_to_end(&mut leftover); + let _ = std::io::Read::read_to_end(buf, &mut leftover); if !leftover.is_empty() { return Err(crate::read::ReadPacketError::LeftoverData { packet_name: #name_litstr.to_string(), data: leftover }); + } } data @@ -312,7 +313,7 @@ pub fn declare_state_packets(input: TokenStream) -> TokenStream { /// Read a packet by its id, ConnectionProtocol, and flow fn read( id: u32, - buf: &mut impl std::io::Read, + buf: &mut std::io::Cursor<&[u8]>, ) -> Result<#serverbound_state_name, crate::read::ReadPacketError> where Self: Sized, @@ -343,7 +344,7 @@ pub fn declare_state_packets(input: TokenStream) -> TokenStream { /// Read a packet by its id, ConnectionProtocol, and flow fn read( id: u32, - buf: &mut impl std::io::Read, + buf: &mut std::io::Cursor<&[u8]>, ) -> Result<#clientbound_state_name, crate::read::ReadPacketError> where Self: Sized, diff --git a/azalea-protocol/src/connect.rs b/azalea-protocol/src/connect.rs index 3fdcecd3..bd55e406 100755..100644 --- a/azalea-protocol/src/connect.rs +++ b/azalea-protocol/src/connect.rs @@ -9,6 +9,7 @@ use crate::read::{read_packet, ReadPacketError}; use crate::write::write_packet; use crate::ServerIpAddress; use azalea_crypto::{Aes128CfbDec, Aes128CfbEnc}; +use bytes::BytesMut; use std::fmt::Debug; use std::marker::PhantomData; use thiserror::Error; @@ -17,6 +18,7 @@ use tokio::net::TcpStream; pub struct ReadConnection<R: ProtocolPacket> { pub read_stream: OwnedReadHalf, + buffer: BytesMut, pub compression_threshold: Option<u32>, pub dec_cipher: Option<Aes128CfbDec>, _reading: PhantomData<R>, @@ -41,6 +43,7 @@ where pub async fn read(&mut self) -> Result<R, ReadPacketError> { read_packet::<R, _>( &mut self.read_stream, + &mut self.buffer, self.compression_threshold, &mut self.dec_cipher, ) @@ -104,6 +107,7 @@ impl Connection<ClientboundHandshakePacket, ServerboundHandshakePacket> { Ok(Connection { reader: ReadConnection { read_stream, + buffer: BytesMut::new(), compression_threshold: None, dec_cipher: None, _reading: PhantomData, @@ -165,6 +169,7 @@ where Connection { reader: ReadConnection { read_stream: connection.reader.read_stream, + buffer: connection.reader.buffer, compression_threshold: connection.reader.compression_threshold, dec_cipher: connection.reader.dec_cipher, _reading: PhantomData, diff --git a/azalea-protocol/src/lib.rs b/azalea-protocol/src/lib.rs index 9fff59f8..4da2ba90 100755 --- a/azalea-protocol/src/lib.rs +++ b/azalea-protocol/src/lib.rs @@ -52,6 +52,8 @@ pub async fn connect(address: ServerAddress) -> Result<(), Box<dyn std::error::E #[cfg(test)] mod tests { + use std::io::Cursor; + use crate::{ packets::login::{ serverbound_hello_packet::{ProfilePublicKeyData, ServerboundHelloPacket}, @@ -60,7 +62,7 @@ mod tests { read::read_packet, write::write_packet, }; - use std::io::Cursor; + use bytes::BytesMut; use uuid::Uuid; #[tokio::test] @@ -75,15 +77,22 @@ mod tests { profile_id: Some(Uuid::from_u128(0)), } .get(); - let mut stream = Cursor::new(Vec::new()); + let mut stream = Vec::new(); write_packet(packet, &mut stream, None, &mut None) .await .unwrap(); - stream.set_position(0); + println!("stream: {stream:?}"); - let _ = read_packet::<ServerboundLoginPacket, _>(&mut stream, None, &mut None) - .await - .unwrap(); + let mut stream = Cursor::new(stream); + + let _ = read_packet::<ServerboundLoginPacket, _>( + &mut stream, + &mut BytesMut::new(), + None, + &mut None, + ) + .await + .unwrap(); } } diff --git a/azalea-protocol/src/packets/game/clientbound_boss_event_packet.rs b/azalea-protocol/src/packets/game/clientbound_boss_event_packet.rs index ed7647e9..3bcf10d2 100644 --- a/azalea-protocol/src/packets/game/clientbound_boss_event_packet.rs +++ b/azalea-protocol/src/packets/game/clientbound_boss_event_packet.rs @@ -1,10 +1,10 @@ -use std::io::{Read, Write}; - use azalea_buf::{ BufReadError, McBuf, McBufReadable, McBufVarReadable, McBufVarWritable, McBufWritable, }; use azalea_chat::component::Component; use azalea_protocol_macros::ClientboundGamePacket; +use std::io::Cursor; +use std::io::Write; use uuid::Uuid; #[derive(Clone, Debug, McBuf, ClientboundGamePacket)] @@ -24,7 +24,7 @@ pub enum Operation { } impl McBufReadable for Operation { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let operation_id = u32::var_read_from(buf)?; Ok(match operation_id { 0 => Operation::Add(AddOperation::read_from(buf)?), @@ -115,7 +115,7 @@ pub struct Properties { } impl McBufReadable for Properties { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let byte = u8::read_from(buf)?; Ok(Self { darken_screen: byte & 1 != 0, diff --git a/azalea-protocol/src/packets/game/clientbound_command_suggestions_packet.rs b/azalea-protocol/src/packets/game/clientbound_command_suggestions_packet.rs index 42c5580f..c6f426a9 100644 --- a/azalea-protocol/src/packets/game/clientbound_command_suggestions_packet.rs +++ b/azalea-protocol/src/packets/game/clientbound_command_suggestions_packet.rs @@ -6,7 +6,7 @@ use azalea_buf::{ McBufWritable, }; use azalea_protocol_macros::ClientboundGamePacket; -use std::io::{Read, Write}; +use std::io::{Cursor, Write}; #[derive(Clone, Debug, ClientboundGamePacket)] pub struct ClientboundCommandSuggestionsPacket { @@ -16,7 +16,7 @@ pub struct ClientboundCommandSuggestionsPacket { } impl McBufReadable for ClientboundCommandSuggestionsPacket { - fn read_from(_buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(_buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { // let id = u32::var_read_from(buf)?; // let start = u32::var_read_from(buf)? as usize; // let length = u32::var_read_from(buf)? as usize; diff --git a/azalea-protocol/src/packets/game/clientbound_commands_packet.rs b/azalea-protocol/src/packets/game/clientbound_commands_packet.rs index e18cf52b..2505d2d9 100644 --- a/azalea-protocol/src/packets/game/clientbound_commands_packet.rs +++ b/azalea-protocol/src/packets/game/clientbound_commands_packet.rs @@ -5,7 +5,8 @@ use azalea_buf::{McBufReadable, McBufWritable}; use azalea_core::ResourceLocation; use azalea_protocol_macros::ClientboundGamePacket; use log::warn; -use std::io::{Read, Write}; +use std::io::Cursor; +use std::io::Write; #[derive(Clone, Debug, McBuf, ClientboundGamePacket)] pub struct ClientboundCommandsPacket { @@ -28,7 +29,7 @@ pub struct BrigadierNumber<T> { max: Option<T>, } impl<T: McBufReadable> McBufReadable for BrigadierNumber<T> { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let flags = u8::read_from(buf)?; let min = if flags & 0x01 != 0 { Some(T::read_from(buf)?) @@ -127,7 +128,7 @@ pub enum BrigadierParser { } impl McBufReadable for BrigadierParser { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let parser_type = u32::var_read_from(buf)?; match parser_type { @@ -203,7 +204,7 @@ impl McBufReadable for BrigadierParser { // TODO: BrigadierNodeStub should have more stuff impl McBufReadable for BrigadierNodeStub { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let flags = u8::read_from(buf)?; if flags > 31 { warn!( diff --git a/azalea-protocol/src/packets/game/clientbound_explode_packet.rs b/azalea-protocol/src/packets/game/clientbound_explode_packet.rs index 97f58782..10a9e9a9 100644 --- a/azalea-protocol/src/packets/game/clientbound_explode_packet.rs +++ b/azalea-protocol/src/packets/game/clientbound_explode_packet.rs @@ -1,7 +1,7 @@ use azalea_buf::{BufReadError, McBufReadable, McBufVarReadable, McBufVarWritable, McBufWritable}; use azalea_core::BlockPos; use azalea_protocol_macros::ClientboundGamePacket; -use std::io::{Read, Write}; +use std::io::{Cursor, Write}; #[derive(Clone, Debug, PartialEq, ClientboundGamePacket)] pub struct ClientboundExplodePacket { @@ -16,7 +16,7 @@ pub struct ClientboundExplodePacket { } impl McBufReadable for ClientboundExplodePacket { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let x = f32::read_from(buf)?; let y = f32::read_from(buf)?; let z = f32::read_from(buf)?; @@ -112,7 +112,7 @@ mod tests { }; let mut buf = Vec::new(); packet.write_into(&mut buf).unwrap(); - let packet2 = ClientboundExplodePacket::read_from(&mut buf.as_slice()).unwrap(); + let packet2 = ClientboundExplodePacket::read_from(&mut Cursor::new(&buf)).unwrap(); assert_eq!(packet, packet2); } } diff --git a/azalea-protocol/src/packets/game/clientbound_level_particles_packet.rs b/azalea-protocol/src/packets/game/clientbound_level_particles_packet.rs index fdde6ec9..705a7540 100644 --- a/azalea-protocol/src/packets/game/clientbound_level_particles_packet.rs +++ b/azalea-protocol/src/packets/game/clientbound_level_particles_packet.rs @@ -1,7 +1,7 @@ use azalea_buf::{BufReadError, McBufReadable, McBufVarReadable, McBufWritable}; use azalea_core::ParticleData; use azalea_protocol_macros::ClientboundGamePacket; -use std::io::{Read, Write}; +use std::io::{Cursor, Write}; #[derive(Clone, Debug, ClientboundGamePacket)] pub struct ClientboundLevelParticlesPacket { @@ -20,7 +20,7 @@ pub struct ClientboundLevelParticlesPacket { } impl McBufReadable for ClientboundLevelParticlesPacket { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let particle_id = u32::var_read_from(buf)?; let override_limiter = bool::read_from(buf)?; let x = f64::read_from(buf)?; diff --git a/azalea-protocol/src/packets/game/clientbound_map_item_data_packet.rs b/azalea-protocol/src/packets/game/clientbound_map_item_data_packet.rs index 6dc4bfe7..4ce71a12 100644 --- a/azalea-protocol/src/packets/game/clientbound_map_item_data_packet.rs +++ b/azalea-protocol/src/packets/game/clientbound_map_item_data_packet.rs @@ -1,9 +1,8 @@ -use std::io::{Read, Write}; - use azalea_buf::{BufReadError, McBuf}; use azalea_buf::{McBufReadable, McBufVarReadable, McBufVarWritable, McBufWritable}; use azalea_chat::component::Component; use azalea_protocol_macros::ClientboundGamePacket; +use std::io::{Cursor, Write}; #[derive(Clone, Debug, ClientboundGamePacket)] pub struct ClientboundMapItemDataPacket { @@ -16,7 +15,7 @@ pub struct ClientboundMapItemDataPacket { } impl McBufReadable for ClientboundMapItemDataPacket { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let map_id = u32::var_read_from(buf)?; let scale = u8::read_from(buf)?; let locked = bool::read_from(buf)?; diff --git a/azalea-protocol/src/packets/game/clientbound_player_abilities_packet.rs b/azalea-protocol/src/packets/game/clientbound_player_abilities_packet.rs index 2196d1c1..192a7bf4 100755 --- a/azalea-protocol/src/packets/game/clientbound_player_abilities_packet.rs +++ b/azalea-protocol/src/packets/game/clientbound_player_abilities_packet.rs @@ -1,7 +1,7 @@ use azalea_buf::{BufReadError, McBuf}; use azalea_buf::{McBufReadable, McBufWritable}; use azalea_protocol_macros::ClientboundGamePacket; -use std::io::{Read, Write}; +use std::io::{Cursor, Write}; #[derive(Clone, Debug, McBuf, ClientboundGamePacket)] pub struct ClientboundPlayerAbilitiesPacket { @@ -20,7 +20,7 @@ pub struct PlayerAbilitiesFlags { } impl McBufReadable for PlayerAbilitiesFlags { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let byte = u8::read_from(buf)?; Ok(PlayerAbilitiesFlags { invulnerable: byte & 1 != 0, diff --git a/azalea-protocol/src/packets/game/clientbound_player_chat_packet.rs b/azalea-protocol/src/packets/game/clientbound_player_chat_packet.rs index c9476a45..94062d87 100644 --- a/azalea-protocol/src/packets/game/clientbound_player_chat_packet.rs +++ b/azalea-protocol/src/packets/game/clientbound_player_chat_packet.rs @@ -95,10 +95,10 @@ mod tests { #[test] fn test_chat_type() { - let chat_type_enum = ChatType::read_from(&mut &[0x06][..]).unwrap(); + let chat_type_enum = ChatType::read_from(&mut Cursor::new(&[0x06])).unwrap(); assert_eq!(chat_type_enum, ChatType::EmoteCommand); assert_eq!( - ChatType::read_from(&mut &[0x07][..]).unwrap(), + ChatType::read_from(&mut Cursor::new(&[0x07])).unwrap(), ChatType::Chat ); } diff --git a/azalea-protocol/src/packets/game/clientbound_player_info_packet.rs b/azalea-protocol/src/packets/game/clientbound_player_info_packet.rs index 8fb2d644..845eed30 100644 --- a/azalea-protocol/src/packets/game/clientbound_player_info_packet.rs +++ b/azalea-protocol/src/packets/game/clientbound_player_info_packet.rs @@ -3,7 +3,7 @@ use azalea_buf::{BufReadError, McBuf}; use azalea_buf::{McBufReadable, McBufWritable}; use azalea_chat::component::Component; use azalea_protocol_macros::ClientboundGamePacket; -use std::io::{Read, Write}; +use std::io::{Cursor, Write}; use uuid::Uuid; #[derive(Clone, Debug, McBuf, ClientboundGamePacket)] @@ -65,7 +65,7 @@ pub struct RemovePlayer { } impl McBufReadable for Action { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let id = u8::read_from(buf)?; Ok(match id { 0 => Action::AddPlayer(Vec::<AddPlayer>::read_from(buf)?), diff --git a/azalea-protocol/src/packets/game/clientbound_player_position_packet.rs b/azalea-protocol/src/packets/game/clientbound_player_position_packet.rs index 842fc258..03a2658e 100644 --- a/azalea-protocol/src/packets/game/clientbound_player_position_packet.rs +++ b/azalea-protocol/src/packets/game/clientbound_player_position_packet.rs @@ -1,7 +1,7 @@ use azalea_buf::{BufReadError, McBuf}; use azalea_buf::{McBufReadable, McBufWritable}; use azalea_protocol_macros::ClientboundGamePacket; -use std::io::{Read, Write}; +use std::io::{Cursor, Write}; #[derive(Clone, Debug, McBuf, ClientboundGamePacket)] pub struct ClientboundPlayerPositionPacket { @@ -28,7 +28,7 @@ pub struct RelativeArguments { } impl McBufReadable for RelativeArguments { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let byte = u8::read_from(buf)?; Ok(RelativeArguments { x: byte & 0b1 != 0, diff --git a/azalea-protocol/src/packets/game/clientbound_recipe_packet.rs b/azalea-protocol/src/packets/game/clientbound_recipe_packet.rs index 4e19a114..b6ac6f3b 100644 --- a/azalea-protocol/src/packets/game/clientbound_recipe_packet.rs +++ b/azalea-protocol/src/packets/game/clientbound_recipe_packet.rs @@ -3,6 +3,7 @@ use azalea_buf::{ }; use azalea_core::ResourceLocation; use azalea_protocol_macros::ClientboundGamePacket; +use std::io::{Cursor, Write}; #[derive(Clone, Debug, ClientboundGamePacket)] pub struct ClientboundRecipePacket { @@ -12,7 +13,7 @@ pub struct ClientboundRecipePacket { } impl McBufWritable for ClientboundRecipePacket { - fn write_into(&self, buf: &mut impl std::io::Write) -> Result<(), std::io::Error> { + fn write_into(&self, buf: &mut impl Write) -> Result<(), std::io::Error> { match self.action { State::Init { .. } => 0, State::Add => 1, @@ -28,7 +29,7 @@ impl McBufWritable for ClientboundRecipePacket { } } impl McBufReadable for ClientboundRecipePacket { - fn read_from(buf: &mut impl std::io::Read) -> Result<Self, azalea_buf::BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, azalea_buf::BufReadError> { let action_id = u32::var_read_from(buf)?; let settings = RecipeBookSettings::read_from(buf)?; let recipes = Vec::<ResourceLocation>::read_from(buf)?; diff --git a/azalea-protocol/src/packets/game/clientbound_section_blocks_update_packet.rs b/azalea-protocol/src/packets/game/clientbound_section_blocks_update_packet.rs index 3f41b3c2..357a30f6 100644 --- a/azalea-protocol/src/packets/game/clientbound_section_blocks_update_packet.rs +++ b/azalea-protocol/src/packets/game/clientbound_section_blocks_update_packet.rs @@ -2,7 +2,7 @@ use azalea_buf::{BufReadError, McBuf}; use azalea_buf::{McBufReadable, McBufVarReadable, McBufVarWritable, McBufWritable}; use azalea_core::{ChunkSectionBlockPos, ChunkSectionPos}; use azalea_protocol_macros::ClientboundGamePacket; -use std::io::{Read, Write}; +use std::io::{Cursor, Write}; #[derive(Clone, Debug, McBuf, ClientboundGamePacket)] pub struct ClientboundSectionBlocksUpdatePacket { @@ -18,7 +18,7 @@ pub struct BlockStateWithPosition { } impl McBufReadable for BlockStateWithPosition { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let data = u64::var_read_from(buf)?; let position_part = data & 4095; let state = (data >> 12) as u32; diff --git a/azalea-protocol/src/packets/game/clientbound_set_equipment_packet.rs b/azalea-protocol/src/packets/game/clientbound_set_equipment_packet.rs index 9398fb69..315f1590 100644 --- a/azalea-protocol/src/packets/game/clientbound_set_equipment_packet.rs +++ b/azalea-protocol/src/packets/game/clientbound_set_equipment_packet.rs @@ -1,8 +1,8 @@ use azalea_buf::{BufReadError, McBuf}; +use azalea_buf::{McBufReadable, McBufWritable}; use azalea_core::Slot; use azalea_protocol_macros::ClientboundGamePacket; - -use azalea_buf::{McBufReadable, McBufWritable}; +use std::io::Cursor; #[derive(Clone, Debug, McBuf, ClientboundGamePacket)] pub struct ClientboundSetEquipmentPacket { @@ -17,7 +17,7 @@ pub struct EquipmentSlots { } impl McBufReadable for EquipmentSlots { - fn read_from(buf: &mut impl std::io::Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let mut slots = vec![]; loop { diff --git a/azalea-protocol/src/packets/game/clientbound_set_objective_packet.rs b/azalea-protocol/src/packets/game/clientbound_set_objective_packet.rs index a9c1c859..0e7e334d 100644 --- a/azalea-protocol/src/packets/game/clientbound_set_objective_packet.rs +++ b/azalea-protocol/src/packets/game/clientbound_set_objective_packet.rs @@ -1,7 +1,7 @@ use azalea_buf::{BufReadError, McBuf, McBufReadable, McBufWritable}; use azalea_chat::component::Component; use azalea_protocol_macros::ClientboundGamePacket; -use std::io::{Read, Write}; +use std::io::{Cursor, Write}; #[derive(Clone, Debug, McBuf, ClientboundGamePacket)] pub struct ClientboundSetObjectivePacket { @@ -17,7 +17,7 @@ pub enum Method { } impl McBufReadable for Method { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { Ok(match u8::read_from(buf)? { 0 => Method::Add(DisplayInfo::read_from(buf)?), 1 => Method::Remove, diff --git a/azalea-protocol/src/packets/game/clientbound_set_player_team_packet.rs b/azalea-protocol/src/packets/game/clientbound_set_player_team_packet.rs index fe5a75f8..a0754ddd 100644 --- a/azalea-protocol/src/packets/game/clientbound_set_player_team_packet.rs +++ b/azalea-protocol/src/packets/game/clientbound_set_player_team_packet.rs @@ -1,8 +1,7 @@ -use std::io::{Read, Write}; - use azalea_buf::{BufReadError, McBuf, McBufReadable, McBufWritable}; use azalea_chat::{component::Component, style::ChatFormatting}; use azalea_protocol_macros::ClientboundGamePacket; +use std::io::{Cursor, Write}; #[derive(Clone, Debug, McBuf, ClientboundGamePacket)] pub struct ClientboundSetPlayerTeamPacket { @@ -20,7 +19,7 @@ pub enum Method { } impl McBufReadable for Method { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { Ok(match u8::read_from(buf)? { 0 => Method::Add((Parameters::read_from(buf)?, PlayerList::read_from(buf)?)), 1 => Method::Remove, diff --git a/azalea-protocol/src/packets/game/clientbound_set_score_packet.rs b/azalea-protocol/src/packets/game/clientbound_set_score_packet.rs index ac1e0bf3..7d055a14 100644 --- a/azalea-protocol/src/packets/game/clientbound_set_score_packet.rs +++ b/azalea-protocol/src/packets/game/clientbound_set_score_packet.rs @@ -1,7 +1,7 @@ use azalea_buf::{BufReadError, McBufReadable, McBufVarReadable, McBufVarWritable, McBufWritable}; use azalea_protocol_macros::ClientboundGamePacket; use std::{ - io::{Read, Write}, + io::{Cursor, Write}, ops::Not, }; @@ -13,7 +13,7 @@ pub struct ClientboundSetScorePacket { } impl McBufReadable for ClientboundSetScorePacket { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let owner = String::read_from(buf)?; let method_id = u32::var_read_from(buf)?; let objective_name = String::read_from(buf)?; diff --git a/azalea-protocol/src/packets/game/clientbound_stop_sound_packet.rs b/azalea-protocol/src/packets/game/clientbound_stop_sound_packet.rs index ee650afb..e0e5db05 100644 --- a/azalea-protocol/src/packets/game/clientbound_stop_sound_packet.rs +++ b/azalea-protocol/src/packets/game/clientbound_stop_sound_packet.rs @@ -1,8 +1,7 @@ -use std::io::{Read, Write}; - use azalea_buf::{BufReadError, McBufReadable, McBufWritable}; use azalea_core::ResourceLocation; use azalea_protocol_macros::ClientboundGamePacket; +use std::io::{Cursor, Write}; use super::clientbound_sound_packet::SoundSource; @@ -13,7 +12,7 @@ pub struct ClientboundStopSoundPacket { } impl McBufReadable for ClientboundStopSoundPacket { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let byte = u8::read_from(buf)?; let source = if byte & 1 != 0 { Some(SoundSource::read_from(buf)?) diff --git a/azalea-protocol/src/packets/game/clientbound_update_advancements_packet.rs b/azalea-protocol/src/packets/game/clientbound_update_advancements_packet.rs index f7adcafa..eb52e133 100644 --- a/azalea-protocol/src/packets/game/clientbound_update_advancements_packet.rs +++ b/azalea-protocol/src/packets/game/clientbound_update_advancements_packet.rs @@ -3,6 +3,7 @@ use azalea_chat::component::Component; use azalea_core::{ResourceLocation, Slot}; use azalea_protocol_macros::ClientboundGamePacket; use std::collections::HashMap; +use std::io::Cursor; #[derive(Clone, Debug, McBuf, ClientboundGamePacket)] pub struct ClientboundUpdateAdvancementsPacket { @@ -63,7 +64,7 @@ impl azalea_buf::McBufWritable for DisplayInfo { } } impl azalea_buf::McBufReadable for DisplayInfo { - fn read_from(buf: &mut impl std::io::Read) -> Result<Self, azalea_buf::BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, azalea_buf::BufReadError> { let title = azalea_buf::McBufReadable::read_from(buf)?; let description = azalea_buf::McBufReadable::read_from(buf)?; let icon = azalea_buf::McBufReadable::read_from(buf)?; diff --git a/azalea-protocol/src/packets/game/clientbound_update_attributes_packet.rs b/azalea-protocol/src/packets/game/clientbound_update_attributes_packet.rs index 5c03d11f..bcccdc3f 100644 --- a/azalea-protocol/src/packets/game/clientbound_update_attributes_packet.rs +++ b/azalea-protocol/src/packets/game/clientbound_update_attributes_packet.rs @@ -2,7 +2,7 @@ use azalea_buf::{BufReadError, McBuf}; use azalea_buf::{McBufReadable, McBufWritable}; use azalea_core::ResourceLocation; use azalea_protocol_macros::ClientboundGamePacket; -use std::io::{Read, Write}; +use std::io::{Cursor, Write}; use uuid::Uuid; #[derive(Clone, Debug, McBuf, ClientboundGamePacket)] @@ -34,7 +34,7 @@ enum Operation { } impl McBufReadable for Operation { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { match u8::read_from(buf)? { 0 => Ok(Operation::Addition), 1 => Ok(Operation::MultiplyBase), diff --git a/azalea-protocol/src/packets/game/clientbound_update_recipes_packet.rs b/azalea-protocol/src/packets/game/clientbound_update_recipes_packet.rs index 8d8ef32b..db31ef78 100644 --- a/azalea-protocol/src/packets/game/clientbound_update_recipes_packet.rs +++ b/azalea-protocol/src/packets/game/clientbound_update_recipes_packet.rs @@ -3,7 +3,7 @@ use azalea_buf::{ }; use azalea_core::{ResourceLocation, Slot}; use azalea_protocol_macros::ClientboundGamePacket; -use std::io::{Read, Write}; +use std::io::{Cursor, Write}; #[derive(Clone, Debug, McBuf, ClientboundGamePacket)] pub struct ClientboundUpdateRecipesPacket { @@ -47,7 +47,7 @@ impl McBufWritable for ShapedRecipe { } } impl McBufReadable for ShapedRecipe { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let width = u32::var_read_from(buf)?.try_into().unwrap(); let height = u32::var_read_from(buf)?.try_into().unwrap(); let group = String::read_from(buf)?; @@ -127,7 +127,7 @@ impl McBufWritable for Recipe { } impl McBufReadable for Recipe { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let recipe_type = ResourceLocation::read_from(buf)?; let identifier = ResourceLocation::read_from(buf)?; diff --git a/azalea-protocol/src/packets/game/clientbound_update_tags_packet.rs b/azalea-protocol/src/packets/game/clientbound_update_tags_packet.rs index 8f5cd04e..3e6e413a 100755 --- a/azalea-protocol/src/packets/game/clientbound_update_tags_packet.rs +++ b/azalea-protocol/src/packets/game/clientbound_update_tags_packet.rs @@ -2,11 +2,9 @@ use azalea_buf::{BufReadError, McBuf, McBufVarReadable, McBufVarWritable}; use azalea_buf::{McBufReadable, McBufWritable}; use azalea_core::ResourceLocation; use azalea_protocol_macros::ClientboundGamePacket; +use std::io::Cursor; use std::ops::Deref; -use std::{ - collections::HashMap, - io::{Read, Write}, -}; +use std::{collections::HashMap, io::Write}; #[derive(Clone, Debug, McBuf, ClientboundGamePacket)] pub struct ClientboundUpdateTagsPacket { @@ -23,7 +21,7 @@ pub struct Tags { pub struct TagMap(HashMap<ResourceLocation, Vec<Tags>>); impl McBufReadable for TagMap { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let length = u32::var_read_from(buf)? as usize; let mut data = HashMap::with_capacity(length); for _ in 0..length { @@ -51,7 +49,7 @@ impl McBufWritable for TagMap { } } impl McBufReadable for Tags { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let name = ResourceLocation::read_from(buf)?; let elements = Vec::<i32>::var_read_from(buf)?; Ok(Tags { name, elements }) diff --git a/azalea-protocol/src/packets/game/serverbound_interact_packet.rs b/azalea-protocol/src/packets/game/serverbound_interact_packet.rs index f40ce406..1904accf 100644 --- a/azalea-protocol/src/packets/game/serverbound_interact_packet.rs +++ b/azalea-protocol/src/packets/game/serverbound_interact_packet.rs @@ -2,7 +2,7 @@ use crate::packets::BufReadError; use azalea_buf::{McBuf, McBufReadable, McBufVarReadable, McBufVarWritable, McBufWritable}; use azalea_core::Vec3; use azalea_protocol_macros::ServerboundGamePacket; -use std::io::{Read, Write}; +use std::io::{Cursor, Write}; #[derive(Clone, Debug, McBuf, ServerboundGamePacket)] pub struct ServerboundInteractPacket { @@ -48,7 +48,7 @@ impl McBufWritable for ActionType { } impl McBufReadable for ActionType { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let action_type = u32::var_read_from(buf)?; match action_type { 0 => { diff --git a/azalea-protocol/src/packets/game/serverbound_player_abilities_packet.rs b/azalea-protocol/src/packets/game/serverbound_player_abilities_packet.rs index 3d9cd930..ab1ae9a0 100644 --- a/azalea-protocol/src/packets/game/serverbound_player_abilities_packet.rs +++ b/azalea-protocol/src/packets/game/serverbound_player_abilities_packet.rs @@ -1,6 +1,7 @@ use crate::packets::BufReadError; use azalea_buf::{McBufReadable, McBufWritable}; use azalea_protocol_macros::ServerboundGamePacket; +use std::io::Cursor; #[derive(Clone, Debug, ServerboundGamePacket)] pub struct ServerboundPlayerAbilitiesPacket { @@ -8,7 +9,7 @@ pub struct ServerboundPlayerAbilitiesPacket { } impl McBufReadable for ServerboundPlayerAbilitiesPacket { - fn read_from(buf: &mut impl std::io::Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let byte = u8::read_from(buf)?; Ok(Self { is_flying: byte & 2 != 0, diff --git a/azalea-protocol/src/packets/game/serverbound_player_input_packet.rs b/azalea-protocol/src/packets/game/serverbound_player_input_packet.rs index ab0a5df0..30d3c3ae 100644 --- a/azalea-protocol/src/packets/game/serverbound_player_input_packet.rs +++ b/azalea-protocol/src/packets/game/serverbound_player_input_packet.rs @@ -1,3 +1,5 @@ +use std::io::Cursor; + use azalea_buf::BufReadError; use azalea_buf::{McBufReadable, McBufWritable}; use azalea_protocol_macros::ServerboundGamePacket; @@ -11,7 +13,7 @@ pub struct ServerboundPlayerInputPacket { } impl McBufReadable for ServerboundPlayerInputPacket { - fn read_from(buf: &mut impl std::io::Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let xxa = f32::read_from(buf)?; let zza = f32::read_from(buf)?; let byte = u8::read_from(buf)?; diff --git a/azalea-protocol/src/packets/game/serverbound_seen_advancements_packet.rs b/azalea-protocol/src/packets/game/serverbound_seen_advancements_packet.rs index 82e90689..5a9b0e48 100644 --- a/azalea-protocol/src/packets/game/serverbound_seen_advancements_packet.rs +++ b/azalea-protocol/src/packets/game/serverbound_seen_advancements_packet.rs @@ -2,6 +2,7 @@ use crate::packets::BufReadError; use azalea_buf::{McBuf, McBufReadable, McBufWritable}; use azalea_core::ResourceLocation; use azalea_protocol_macros::ServerboundGamePacket; +use std::io::Cursor; #[derive(Clone, Debug, ServerboundGamePacket)] pub struct ServerboundSeenAdvancementsPacket { @@ -16,7 +17,7 @@ pub enum Action { } impl McBufReadable for ServerboundSeenAdvancementsPacket { - fn read_from(buf: &mut impl std::io::Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let action = Action::read_from(buf)?; let tab = if action == Action::OpenedTab { Some(ResourceLocation::read_from(buf)?) diff --git a/azalea-protocol/src/packets/game/serverbound_set_command_block_packet.rs b/azalea-protocol/src/packets/game/serverbound_set_command_block_packet.rs index 66bbb91a..7edb9719 100644 --- a/azalea-protocol/src/packets/game/serverbound_set_command_block_packet.rs +++ b/azalea-protocol/src/packets/game/serverbound_set_command_block_packet.rs @@ -2,6 +2,7 @@ use crate::packets::McBufWritable; use azalea_buf::{BufReadError, McBuf, McBufReadable}; use azalea_core::BlockPos; use azalea_protocol_macros::ServerboundGamePacket; +use std::io::Cursor; #[derive(Clone, Debug, ServerboundGamePacket)] pub struct ServerboundSetCommandBlockPacket { @@ -22,7 +23,7 @@ pub enum Mode { } impl McBufReadable for ServerboundSetCommandBlockPacket { - fn read_from(buf: &mut impl std::io::Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let pos = BlockPos::read_from(buf)?; let command = String::read_from(buf)?; let mode = Mode::read_from(buf)?; diff --git a/azalea-protocol/src/packets/game/serverbound_set_jigsaw_block_packet.rs b/azalea-protocol/src/packets/game/serverbound_set_jigsaw_block_packet.rs index 94653bc7..78f77754 100644 --- a/azalea-protocol/src/packets/game/serverbound_set_jigsaw_block_packet.rs +++ b/azalea-protocol/src/packets/game/serverbound_set_jigsaw_block_packet.rs @@ -5,7 +5,8 @@ use azalea_buf::McBufReadable; use azalea_core::BlockPos; use azalea_core::ResourceLocation; use azalea_protocol_macros::ServerboundGamePacket; -use std::io::{Read, Write}; +use std::io::Cursor; +use std::io::Write; #[derive(Clone, Debug, McBuf, ServerboundGamePacket)] pub struct ServerboundSetJigsawBlockPacket { @@ -23,7 +24,7 @@ pub enum JointType { } impl McBufReadable for JointType { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let name = String::read_from(buf)?; match name.as_str() { "rollable" => Ok(JointType::Rollable), diff --git a/azalea-protocol/src/packets/game/serverbound_set_structure_block_packet.rs b/azalea-protocol/src/packets/game/serverbound_set_structure_block_packet.rs index 0851857f..901d3f89 100644 --- a/azalea-protocol/src/packets/game/serverbound_set_structure_block_packet.rs +++ b/azalea-protocol/src/packets/game/serverbound_set_structure_block_packet.rs @@ -3,7 +3,7 @@ use azalea_buf::McBuf; use azalea_buf::{McBufReadable, McBufWritable}; use azalea_core::BlockPos; use azalea_protocol_macros::ServerboundGamePacket; -use std::io::{Read, Write}; +use std::io::{Cursor, Write}; #[derive(Clone, Debug, McBuf, ServerboundGamePacket)] pub struct ServerboundSetStructureBlockPacket { @@ -68,7 +68,7 @@ pub struct Flags { } impl McBufReadable for Flags { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let byte = u8::read_from(buf)?; Ok(Self { ignore_entities: byte & 1 != 0, diff --git a/azalea-protocol/src/packets/game/serverbound_use_item_on_packet.rs b/azalea-protocol/src/packets/game/serverbound_use_item_on_packet.rs index ab3fa137..ded977aa 100644 --- a/azalea-protocol/src/packets/game/serverbound_use_item_on_packet.rs +++ b/azalea-protocol/src/packets/game/serverbound_use_item_on_packet.rs @@ -2,7 +2,7 @@ use crate::packets::game::serverbound_interact_packet::InteractionHand; use azalea_buf::{BufReadError, McBuf, McBufReadable, McBufWritable}; use azalea_core::{BlockPos, Direction, Vec3}; use azalea_protocol_macros::ServerboundGamePacket; -use std::io::{Read, Write}; +use std::io::{Cursor, Write}; #[derive(Clone, Debug, McBuf, ServerboundGamePacket)] pub struct ServerboundUseItemOnPacket { @@ -33,7 +33,7 @@ impl McBufWritable for BlockHitResult { } impl McBufReadable for BlockHitResult { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let block_pos = BlockPos::read_from(buf)?; let direction = Direction::read_from(buf)?; let cursor_x = f32::read_from(buf)?; 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 6ecbfb66..6976298a 100755 --- a/azalea-protocol/src/packets/login/clientbound_login_compression_packet.rs +++ b/azalea-protocol/src/packets/login/clientbound_login_compression_packet.rs @@ -1,31 +1,9 @@ -use super::ClientboundLoginPacket; -use azalea_buf::{BufReadError, McBufVarReadable, McBufVarWritable}; -use std::{ - hash::Hash, - io::{Read, Write}, -}; +use azalea_buf::McBuf; +use azalea_protocol_macros::ClientboundLoginPacket; +use std::hash::Hash; -#[derive(Hash, Clone, Debug)] +#[derive(Hash, Clone, Debug, ClientboundLoginPacket, McBuf)] pub struct ClientboundLoginCompressionPacket { + #[var] pub compression_threshold: i32, } - -impl ClientboundLoginCompressionPacket { - pub fn get(self) -> ClientboundLoginPacket { - ClientboundLoginPacket::LoginCompression(self) - } - - pub fn write(&self, buf: &mut impl Write) -> Result<(), std::io::Error> { - self.compression_threshold.var_write_into(buf)?; - Ok(()) - } - - pub fn read(buf: &mut impl Read) -> Result<ClientboundLoginPacket, BufReadError> { - let compression_threshold = i32::var_read_from(buf)?; - - Ok(ClientboundLoginCompressionPacket { - compression_threshold, - } - .get()) - } -} diff --git a/azalea-protocol/src/packets/login/serverbound_hello_packet.rs b/azalea-protocol/src/packets/login/serverbound_hello_packet.rs index 4d94092e..5e1422fb 100755 --- a/azalea-protocol/src/packets/login/serverbound_hello_packet.rs +++ b/azalea-protocol/src/packets/login/serverbound_hello_packet.rs @@ -18,6 +18,8 @@ pub struct ProfilePublicKeyData { #[cfg(test)] mod tests { + use std::io::Cursor; + use super::*; use azalea_buf::{McBufReadable, McBufWritable}; @@ -28,9 +30,9 @@ mod tests { public_key: None, profile_id: Some(Uuid::from_u128(0)), }; - let mut buf = Vec::new(); + let mut buf: Vec<u8> = Vec::new(); packet.write_into(&mut buf).unwrap(); - let packet2 = ServerboundHelloPacket::read_from(&mut buf.as_slice()).unwrap(); + let packet2 = ServerboundHelloPacket::read_from(&mut Cursor::new(&buf)).unwrap(); assert_eq!(packet, packet2); } } diff --git a/azalea-protocol/src/packets/login/serverbound_key_packet.rs b/azalea-protocol/src/packets/login/serverbound_key_packet.rs index ba4bcb8a..23b3659b 100644 --- a/azalea-protocol/src/packets/login/serverbound_key_packet.rs +++ b/azalea-protocol/src/packets/login/serverbound_key_packet.rs @@ -1,7 +1,7 @@ use azalea_buf::{BufReadError, McBuf}; use azalea_crypto::SaltSignaturePair; use azalea_protocol_macros::ServerboundLoginPacket; -use std::io::{Read, Write}; +use std::io::{Cursor, Write}; use azalea_buf::{McBufReadable, McBufWritable}; @@ -18,7 +18,7 @@ pub enum NonceOrSaltSignature { } impl McBufReadable for NonceOrSaltSignature { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let is_nonce = bool::read_from(buf)?; if is_nonce { Ok(NonceOrSaltSignature::Nonce(Vec::<u8>::read_from(buf)?)) diff --git a/azalea-protocol/src/packets/mod.rs b/azalea-protocol/src/packets/mod.rs index 110929a1..f7270b51 100644 --- a/azalea-protocol/src/packets/mod.rs +++ b/azalea-protocol/src/packets/mod.rs @@ -5,7 +5,7 @@ pub mod status; use crate::read::ReadPacketError; use azalea_buf::{BufReadError, McBufVarReadable, McBufVarWritable, McBufWritable}; -use std::io::{Read, Write}; +use std::io::{Cursor, Write}; // TODO: rename the packet files to just like clientbound_add_entity instead of clientbound_add_entity_packet @@ -39,13 +39,13 @@ where fn id(&self) -> u32; /// Read a packet by its id, ConnectionProtocol, and flow - fn read(id: u32, buf: &mut impl Read) -> Result<Self, ReadPacketError>; + fn read(id: u32, buf: &mut Cursor<&[u8]>) -> Result<Self, ReadPacketError>; fn write(&self, buf: &mut impl Write) -> Result<(), std::io::Error>; } impl azalea_buf::McBufReadable for ConnectionProtocol { - fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> { let id = i32::var_read_from(buf)?; ConnectionProtocol::from_i32(id).ok_or(BufReadError::UnexpectedEnumVariant { id }) } 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 f7a349e2..f8b46b8d 100755 --- a/azalea-protocol/src/packets/status/clientbound_status_response_packet.rs +++ b/azalea-protocol/src/packets/status/clientbound_status_response_packet.rs @@ -1,14 +1,14 @@ -use super::ClientboundStatusPacket; -use azalea_buf::{BufReadError, McBufReadable}; +use azalea_buf::{BufReadError, McBufReadable, McBufWritable}; use azalea_chat::component::Component; +use azalea_protocol_macros::ClientboundStatusPacket; use serde::Deserialize; use serde_json::Value; -use std::io::{Read, Write}; +use std::io::{Cursor, Write}; #[derive(Clone, Debug, Deserialize)] pub struct Version { pub name: Component, - pub protocol: u32, + pub protocol: i32, } #[derive(Clone, Debug, Deserialize)] @@ -26,7 +26,7 @@ pub struct Players { } // the entire packet is just json, which is why it has deserialize -#[derive(Clone, Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize, ClientboundStatusPacket)] pub struct ClientboundStatusResponsePacket { pub description: Component, pub favicon: Option<String>, @@ -34,21 +34,17 @@ pub struct ClientboundStatusResponsePacket { pub version: Version, } -impl ClientboundStatusResponsePacket { - pub fn get(self) -> ClientboundStatusPacket { - ClientboundStatusPacket::StatusResponse(self) - } - - pub fn write(&self, _buf: &mut impl Write) -> Result<(), std::io::Error> { - Ok(()) - } - - pub fn read(buf: &mut impl Read) -> Result<ClientboundStatusPacket, BufReadError> { +impl McBufReadable for ClientboundStatusResponsePacket { + fn read_from(buf: &mut Cursor<&[u8]>) -> Result<ClientboundStatusResponsePacket, BufReadError> { let status_string = String::read_from(buf)?; let status_json: Value = serde_json::from_str(status_string.as_str())?; - let packet = ClientboundStatusResponsePacket::deserialize(status_json)?.get(); + Ok(ClientboundStatusResponsePacket::deserialize(status_json)?) + } +} - Ok(packet) +impl McBufWritable for ClientboundStatusResponsePacket { + fn write_into(&self, _buf: &mut impl Write) -> Result<(), std::io::Error> { + todo!() } } diff --git a/azalea-protocol/src/read.rs b/azalea-protocol/src/read.rs index 8a2aaf7d..eceede9d 100755..100644 --- a/azalea-protocol/src/read.rs +++ b/azalea-protocol/src/read.rs @@ -1,9 +1,12 @@ use crate::packets::ProtocolPacket; +use azalea_buf::BufReadError; use azalea_buf::McBufVarReadable; -use azalea_buf::{read_varint_async, BufReadError}; use azalea_crypto::Aes128CfbDec; +use bytes::Buf; +use bytes::BytesMut; use flate2::read::ZlibDecoder; use log::{log_enabled, trace}; +use std::io::Cursor; use std::{ cell::Cell, io::Read, @@ -52,34 +55,82 @@ pub enum FrameSplitterError { source: std::io::Error, }, #[error("Packet is longer than {max} bytes (is {size})")] - BadLength { max: u32, size: u32 }, + BadLength { max: usize, size: usize }, + #[error("Connection reset by peer")] + ConnectionReset, + #[error("Connection closed")] + ConnectionClosed, } -async fn frame_splitter<R: ?Sized>(mut stream: &mut R) -> Result<Vec<u8>, FrameSplitterError> -where - R: AsyncRead + std::marker::Unpin + std::marker::Send, -{ +/// Read a length, then read that amount of bytes from BytesMut. If there's not +/// enough data, return None +fn parse_frame(buffer: &mut BytesMut) -> Result<BytesMut, FrameSplitterError> { + // copy the buffer first and read from the copy, then once we make sure + // the packet is all good we read it fully + let mut buffer_copy = Cursor::new(&buffer[..]); // Packet Length - let length = read_varint_async(&mut stream).await? as u32; + let length = match u32::var_read_from(&mut buffer_copy) { + Ok(length) => length as usize, + Err(err) => match err { + BufReadError::Io(io_err) => return Err(FrameSplitterError::Io { source: io_err }), + _ => return Err(err.into()), + }, + }; - // TODO: read individual tcp packets so we don't need this - // https://github.com/tokio-rs/tokio/blob/master/examples/print_each_packet.rs - let max_length: u32 = 2u32.pow(20u32); // 1mb, arbitrary - if length > max_length { - // minecraft *probably* won't send packets bigger than this + if length > buffer_copy.get_ref().len() { return Err(FrameSplitterError::BadLength { - max: max_length, + max: buffer_copy.get_ref().len(), size: length, }); } - let mut buf = vec![0; length as usize]; - stream.read_exact(&mut buf).await?; + // we read from the copy and we know it's legit, so we can take those bytes + // from the real buffer now + + // the length of the varint that says the length of the whole packet + let varint_length = buffer.len() - buffer_copy.remaining(); + let _ = buffer.split_to(varint_length); + let data = buffer.split_to(length); - Ok(buf) + Ok(data) +} + +async fn frame_splitter<'a, R: ?Sized + Sized>( + stream: &mut R, + buffer: &'a mut BytesMut, +) -> Result<Vec<u8>, FrameSplitterError> +where + R: AsyncRead + std::marker::Unpin + std::marker::Send, +{ + // https://tokio.rs/tokio/tutorial/framing + loop { + let read_frame = parse_frame(buffer); + match read_frame { + Ok(frame) => return Ok(frame.to_vec()), + Err(err) => match err { + FrameSplitterError::BadLength { .. } | FrameSplitterError::Io { .. } => { + // we probably just haven't read enough yet + } + _ => return Err(err), + }, + } + + let read_buf: usize = AsyncReadExt::read_buf(stream, buffer).await?; + if 0 == read_buf { + // The remote closed the connection. For this to be + // a clean shutdown, there should be no data in the + // read buffer. If there is, this means that the + // peer closed the socket while sending a frame. + if buffer.as_ref().is_empty() { + return Err(FrameSplitterError::ConnectionClosed); + } else { + return Err(FrameSplitterError::ConnectionReset); + } + } + } } -fn packet_decoder<P: ProtocolPacket>(stream: &mut impl Read) -> Result<P, ReadPacketError> { +fn packet_decoder<P: ProtocolPacket>(stream: &mut Cursor<&[u8]>) -> Result<P, ReadPacketError> { // Packet ID let packet_id = u32::var_read_from(stream).map_err(|e| ReadPacketError::ReadPacketId { source: e })?; @@ -112,7 +163,7 @@ pub enum DecompressionError { } fn compression_decoder( - stream: &mut impl Read, + stream: &mut Cursor<&[u8]>, compression_threshold: u32, ) -> Result<Vec<u8>, DecompressionError> { // Data Length @@ -120,7 +171,7 @@ fn compression_decoder( if n == 0 { // no data size, no compression let mut buf = vec![]; - stream.read_to_end(&mut buf)?; + std::io::Read::read_to_end(stream, &mut buf)?; return Ok(buf); } @@ -183,6 +234,7 @@ where pub async fn read_packet<'a, P: ProtocolPacket, R>( stream: &'a mut R, + buffer: &mut BytesMut, compression_threshold: Option<u32>, cipher: &mut Option<Aes128CfbDec>, ) -> Result<P, ReadPacketError> @@ -195,10 +247,10 @@ where stream: &mut Pin::new(stream), }; - let mut buf = frame_splitter(&mut encrypted_stream).await?; + let mut buf = frame_splitter(&mut encrypted_stream, buffer).await?; if let Some(compression_threshold) = compression_threshold { - buf = compression_decoder(&mut buf.as_slice(), compression_threshold)?; + buf = compression_decoder(&mut Cursor::new(&buf[..]), compression_threshold)?; } if log_enabled!(log::Level::Trace) { @@ -213,7 +265,7 @@ where trace!("Reading packet with bytes: {buf_string}"); } - let packet = packet_decoder(&mut buf.as_slice())?; + let packet = packet_decoder(&mut Cursor::new(&buf[..]))?; Ok(packet) } @@ -226,7 +278,7 @@ mod tests { #[tokio::test] async fn test_read_packet() { - let mut buf = Cursor::new(vec![ + let mut buf: Cursor<&[u8]> = Cursor::new(&[ 51, 0, 12, 177, 250, 155, 132, 106, 60, 218, 161, 217, 90, 157, 105, 57, 206, 20, 0, 5, 104, 101, 108, 108, 111, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 116, 123, 34, 101, 120, 116, 114, 97, 34, 58, 91, 123, 34, 99, 111, 108, 111, 114, 34, 58, |
