use std::{ io::{Error, Read, Write}, marker::PhantomData, pin::Pin, task::{Context, Poll}, }; use aes::cipher::BlockSizeUser; use bytes::Bytes; use codec::var_int::VarInt; use hybrid_array::{Array, sizes::U1}; use pumpkin_util::{ resource_location::ResourceLocation, text::{TextComponent, style::Style}, version::JavaMinecraftVersion, }; use ser::{ReadingError, WritingError}; use serde::{ Deserialize, Deserializer, Serialize, Serializer, de::{DeserializeSeed, SeqAccess, Visitor}, }; use thiserror::Error; use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; use crate::packet::{MultiVersionJavaPacket, Packet}; pub mod bedrock; pub mod codec; pub mod java; pub mod packet; #[cfg(feature = "query")] pub mod query; pub mod ser; pub mod serial; pub const MAX_PACKET_SIZE: u64 = 2_097_152; pub const MAX_PACKET_DATA_SIZE: usize = 8_388_608; pub type FixedBitSet = Box<[u8]>; /// Represents a compression threshold. /// /// The threshold determines the minimum size of data that should be compressed. /// Data smaller than the threshold will not be compressed. pub type CompressionThreshold = usize; /// Represents a compression level. /// /// The level controls the amount of compression applied to the data. /// Higher levels generally result in higher compression ratios, but also /// increase CPU usage. pub type CompressionLevel = u32; #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum ConnectionState { HandShake, Status, Login, Transfer, Config, Play, } pub struct InvalidConnectionState; impl TryFrom for ConnectionState { type Error = InvalidConnectionState; fn try_from(value: VarInt) -> Result { let value = value.0; match value { 1 => Ok(Self::Status), 2 => Ok(Self::Login), 3 => Ok(Self::Transfer), _ => Err(InvalidConnectionState), } } } struct IdOrVisitor(PhantomData); impl<'de, T: Deserialize<'de>> Visitor<'de> for IdOrVisitor { type Value = IdOr; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { formatter.write_str("A VarInt followed by a value if the VarInt is 0") } fn visit_seq>(self, mut seq: A) -> Result { enum IdOrStateDeserializer { Init, Id(u16), Value(T), } impl<'de, T: Deserialize<'de>> DeserializeSeed<'de> for &mut IdOrStateDeserializer { type Value = (); fn deserialize>( self, deserializer: D, ) -> Result { match self { IdOrStateDeserializer::Init => { // Get the VarInt let id = VarInt::deserialize(deserializer)?; *self = IdOrStateDeserializer::::Id(id.0.try_into().map_err(|_| { serde::de::Error::custom(format!( "{} cannot be mapped to a registry id", id.0 )) })?); } IdOrStateDeserializer::Id(id) => { debug_assert_eq!(*id, 0); // Get the data let value = T::deserialize(deserializer)?; *self = IdOrStateDeserializer::Value(value); } IdOrStateDeserializer::Value(_) => { return Err(serde::de::Error::custom("Unreachable state reached")); } } Ok(()) } } let mut state = IdOrStateDeserializer::::Init; let _ = seq.next_element_seed(&mut state)?; match state { IdOrStateDeserializer::Id(id) => { if id > 0 { return Ok(IdOr::Id(id - 1)); } } _ => return Err(serde::de::Error::custom("Unreachable state reached")), } let _ = seq.next_element_seed(&mut state)?; match state { IdOrStateDeserializer::Value(val) => Ok(IdOr::Value(val)), _ => Err(serde::de::Error::custom("Unreachable state reached")), } } } #[derive(PartialEq, Eq, Clone)] pub enum IdOr { Id(u16), Value(T), } impl<'de, T: Deserialize<'de>> Deserialize<'de> for IdOr { fn deserialize>(deserializer: D) -> Result { deserializer.deserialize_seq(IdOrVisitor(PhantomData)) } } #[expect(clippy::trait_duplication_in_bounds)] impl Serialize for IdOr { fn serialize(&self, serializer: S) -> Result { match self { Self::Id(id) => VarInt::from(*id + 1).serialize(serializer), Self::Value(value) => { #[derive(Serialize)] struct NetworkRepr { zero_id: VarInt, value: T, } NetworkRepr { zero_id: 0.into(), value, } .serialize(serializer) } } } } #[derive(Serialize, Deserialize, Clone, PartialEq)] pub struct SoundEvent { pub sound_name: ResourceLocation, pub range: Option, } type Aes128Cfb8Dec = cfb8::Decryptor; pub struct StreamDecryptor { cipher: Aes128Cfb8Dec, read: R, } impl StreamDecryptor { pub const fn new(cipher: Aes128Cfb8Dec, stream: R) -> Self { Self { cipher, read: stream, } } } impl AsyncRead for StreamDecryptor { fn poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll> { let ref_self = self.get_mut(); let read = Pin::new(&mut ref_self.read); let cipher = &mut ref_self.cipher; // Get the starting position let original_fill = buf.filled().len(); // Read the raw data let internal_poll = read.poll_read(cx, buf); if matches!(internal_poll, Poll::Ready(Ok(()))) { // Decrypt the raw data in-place, note that our block size is 1 byte, so this is always safe for block in buf.filled_mut()[original_fill..].chunks_mut(Aes128Cfb8Dec::block_size()) { cipher.decrypt(block); } } internal_poll } } type Aes128Cfb8Enc = cfb8::Encryptor; ///NOTE: This makes lots of small writes; make sure there is a buffer somewhere down the line pub struct StreamEncryptor { cipher: Aes128Cfb8Enc, write: W, last_unwritten_encrypted_byte: Option, } impl StreamEncryptor { pub fn new(cipher: Aes128Cfb8Enc, stream: W) -> Self { debug_assert_eq!(Aes128Cfb8Enc::block_size(), 1); Self { cipher, write: stream, last_unwritten_encrypted_byte: None, } } } impl AsyncWrite for StreamEncryptor { fn poll_write( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll> { let ref_self = self.get_mut(); let cipher = &mut ref_self.cipher; let mut total_written = 0; // Decrypt the raw data, note that our block size is 1 byte, so this is always safe for block in buf.chunks(Aes128Cfb8Enc::block_size()) { let mut out = [0u8]; if let Some(out_to_use) = ref_self.last_unwritten_encrypted_byte { // This assumes that this `poll_write` is called on the same stream of bytes which I // think is a fair assumption, since thats an invariant for the TCP stream anyway. // This should never panic out[0] = out_to_use; } else { let out_block: &mut Array = (&mut out[..]) .try_into() .map_err(|_| Error::other("Output slice size does not match block size"))?; cipher .encrypt_b2b(block, out_block) .map_err(|_| Error::other("Encryption failed"))?; } let write = Pin::new(&mut ref_self.write); match write.poll_write(cx, &out) { Poll::Pending => { ref_self.last_unwritten_encrypted_byte = Some(out[0]); if total_written == 0 { //If we didn't write anything, return pending return Poll::Pending; } // Otherwise, we actually did write something return Poll::Ready(Ok(total_written)); } Poll::Ready(result) => { ref_self.last_unwritten_encrypted_byte = None; match result { Ok(written) => total_written += written, Err(err) => return Poll::Ready(Err(err)), } } } } Poll::Ready(Ok(total_written)) } fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let ref_self = self.get_mut(); let write = Pin::new(&mut ref_self.write); write.poll_flush(cx) } fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let ref_self = self.get_mut(); let write = Pin::new(&mut ref_self.write); write.poll_shutdown(cx) } } pub struct RawPacket { pub id: i32, pub payload: Bytes, } pub trait ClientPacket: MultiVersionJavaPacket { fn write_packet_data( &self, write: impl Write, version: &JavaMinecraftVersion, ) -> Result<(), WritingError>; } pub trait ServerPacket: MultiVersionJavaPacket + Sized { fn read(read: impl Read, version: &JavaMinecraftVersion) -> Result; } pub trait BClientPacket: Packet { fn write_packet(&self, writer: impl Write) -> Result<(), Error>; } pub trait BServerPacket: Packet + Sized { fn read(read: impl Read) -> Result; } /// Errors that can occur during packet encoding. #[derive(Error, Debug)] pub enum PacketEncodeError { #[error("Packet exceeds maximum length: {0}")] TooLong(usize), #[error("Compression failed {0}")] CompressionFailed(String), #[error("Writing packet failed: {0}")] Message(String), } #[derive(Error, Debug)] pub enum PacketDecodeError { #[error("failed to decode packet ID")] DecodeID, #[error("packet exceeds maximum length")] TooLong, #[error("packet length is out of bounds")] OutOfBounds, #[error("malformed packet length VarInt: {0}")] MalformedLength(String), #[error("failed to decompress packet: {0}")] FailedDecompression(String), // Updated to include error details #[error("packet is uncompressed but greater than the threshold")] NotCompressed, #[error("the connection has closed")] ConnectionClosed, #[error("{0}")] Message(String), } impl From for PacketDecodeError { fn from(value: ReadingError) -> Self { Self::FailedDecompression(value.to_string()) } } #[derive(Serialize, Clone)] pub struct StatusResponse { /// The version on which the server is running. (Optional) pub version: Option, /// Information about currently connected players. (Optional) pub players: Option, /// The description displayed, also called MOTD (Message of the Day). (Optional) pub description: String, /// The icon displayed. (Optional) pub favicon: Option, /// Whether players are forced to use secure chat. pub enforce_secure_chat: bool, } #[derive(Serialize, Clone)] pub struct Version { /// The name of the version (e.g. 1.21.4) pub name: String, /// The protocol version (e.g. 767) pub protocol: u32, } #[derive(Serialize, Clone)] pub struct Players { /// The maximum player count that the server allows. pub max: u32, /// The current online player count. pub online: u32, /// Information about currently connected players. /// Note: players can disable listing here. pub sample: Vec, } #[derive(Serialize, Clone)] pub struct Sample { /// The player's name. pub name: String, /// The player's UUID. pub id: String, } // basically game profile #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Property { pub name: Box, // base 64 pub value: Box, // base 64 pub signature: Option>, } #[derive(Serialize)] pub struct KnownPack<'a> { pub namespace: &'a str, pub id: &'a str, pub version: &'a str, } #[derive(Serialize, Clone)] pub enum NumberFormat { /// Show nothing. Blank, /// The styling to be used when formatting the score number. Styled(Style), /// The text to be used as a placeholder. Fixed(TextComponent), } /// For the first 8 values set means relative value while unset means absolute #[derive(Debug, PartialEq, Eq, Hash)] pub enum PositionFlag { X, Y, Z, YRot, XRot, DeltaX, DeltaY, DeltaZ, RotateDelta, } impl PositionFlag { const fn get_mask(&self) -> i32 { match self { Self::X => 1 << 0, Self::Y => 1 << 1, Self::Z => 1 << 2, Self::YRot => 1 << 3, Self::XRot => 1 << 4, Self::DeltaX => 1 << 5, Self::DeltaY => 1 << 6, Self::DeltaZ => 1 << 7, Self::RotateDelta => 1 << 8, } } #[must_use] pub fn get_bitfield(flags: &[Self]) -> i32 { flags.iter().fold(0, |acc, flag| acc | flag.get_mask()) } } pub enum Label { BuiltIn(LinkType), TextComponent(Box), } impl Serialize for Label { fn serialize(&self, serializer: S) -> Result { match self { Self::BuiltIn(link_type) => link_type.serialize(serializer), Self::TextComponent(component) => component.serialize(serializer), } } } #[derive(Serialize)] pub struct Link<'a> { pub is_built_in: bool, pub label: Label, pub url: &'a String, } impl<'a> Link<'a> { #[must_use] pub const fn new(label: Label, url: &'a String) -> Self { Self { is_built_in: match label { Label::BuiltIn(_) => true, Label::TextComponent(_) => false, }, label, url, } } } #[derive(Clone, Copy)] #[repr(i32)] pub enum LinkType { BugReport = 0, CommunityGuidelines = 1, Support = 2, Status = 3, Feedback = 4, Community = 5, Website = 6, Forums = 7, News = 8, Announcements = 9, } impl Serialize for LinkType { fn serialize(&self, serializer: S) -> Result { VarInt(*self as i32).serialize(serializer) } } #[cfg(test)] mod test { use serde::{Deserialize, Serialize}; use crate::{ IdOr, SoundEvent, ser::{deserializer::Deserializer, serializer::Serializer}, }; #[test] fn serde_id_or_id() -> Result<(), Box> { let mut buf = Vec::new(); let id = IdOr::::Id(0); id.serialize(&mut Serializer::new(&mut buf))?; let deser_id = IdOr::::deserialize(&mut Deserializer::new(buf.as_slice()))?; assert!(id == deser_id); Ok(()) } #[test] fn serde_id_or_value() -> Result<(), Box> { let mut buf = Vec::new(); let event = SoundEvent { sound_name: "test".to_string(), range: Some(1.0), }; let id = IdOr::::Value(event); id.serialize(&mut Serializer::new(&mut buf))?; let deser_id = IdOr::::deserialize(&mut Deserializer::new(buf.as_slice()))?; assert!(id == deser_id); Ok(()) } }