aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authormat <27899617+mat-1@users.noreply.github.com>2022-08-06 07:22:19 +0000
committerGitHub <noreply@github.com>2022-08-06 02:22:19 -0500
commit5a9fca0ca9cdb46f4b866781f219756c89e2293a (patch)
treeb006e28b91a181734fb9702bb6ec510f5b2af3df
parent1d48c3fe34edd4e2295f54bd3d79f81f58c38a8e (diff)
downloadazalea-drasl-5a9fca0ca9cdb46f4b866781f219756c89e2293a.tar.xz
Better errors (#14)
* make reading use thiserror * finish implementing all the error things * clippy warnings related to ok_or * fix some errors in other places * thiserror in more places * don't use closures in a couple places * errors in writing packet * rip backtraces * change some BufReadError::Custom to UnexpectedEnumVariant * Errors say what packet is bad * error on leftover data and fix it wasn't reading the properties for gameprofile
-rwxr-xr-xCargo.lock20
-rwxr-xr-xazalea-auth/Cargo.toml1
-rwxr-xr-xazalea-auth/src/game_profile.rs12
-rw-r--r--azalea-buf/Cargo.toml9
-rw-r--r--azalea-buf/buf-macros/Cargo.toml2
-rw-r--r--azalea-buf/buf-macros/src/lib.rs15
-rw-r--r--azalea-buf/src/definitions.rs4
-rw-r--r--azalea-buf/src/lib.rs2
-rw-r--r--azalea-buf/src/read.rs196
-rw-r--r--azalea-buf/src/serializable_uuid.rs4
-rwxr-xr-xazalea-chat/Cargo.toml2
-rwxr-xr-xazalea-chat/src/component.rs9
-rwxr-xr-xazalea-chat/src/style.rs17
-rwxr-xr-xazalea-chat/src/text_component.rs2
-rwxr-xr-xazalea-client/Cargo.toml6
-rw-r--r--azalea-client/src/account.rs4
-rw-r--r--azalea-client/src/client.rs91
-rw-r--r--azalea-client/src/movement.rs23
-rwxr-xr-xazalea-client/src/ping.rs24
-rwxr-xr-xazalea-core/src/difficulty.rs4
-rwxr-xr-xazalea-core/src/game_type.rs33
-rw-r--r--azalea-core/src/particle/mod.rs8
-rw-r--r--azalea-core/src/position.rs8
-rwxr-xr-xazalea-core/src/resource_location.rs6
-rw-r--r--azalea-core/src/slot.rs4
-rw-r--r--azalea-entity/src/data.rs14
-rwxr-xr-xazalea-nbt/src/decode.rs3
-rwxr-xr-xazalea-protocol/Cargo.toml2
-rw-r--r--[-rwxr-xr-x]azalea-protocol/packet-macros/src/lib.rs33
-rwxr-xr-xazalea-protocol/src/connect.rs25
-rwxr-xr-xazalea-protocol/src/packets/game/clientbound_declare_commands_packet.rs11
-rw-r--r--azalea-protocol/src/packets/game/clientbound_level_particles_packet.rs4
-rwxr-xr-xazalea-protocol/src/packets/game/clientbound_player_abilities_packet.rs4
-rw-r--r--azalea-protocol/src/packets/game/clientbound_player_chat_packet.rs8
-rw-r--r--azalea-protocol/src/packets/game/clientbound_player_info_packet.rs6
-rw-r--r--azalea-protocol/src/packets/game/clientbound_player_position_packet.rs4
-rw-r--r--azalea-protocol/src/packets/game/clientbound_recipe_packet.rs4
-rw-r--r--azalea-protocol/src/packets/game/clientbound_section_blocks_update_packet.rs4
-rw-r--r--azalea-protocol/src/packets/game/clientbound_set_equipment_packet.rs12
-rw-r--r--azalea-protocol/src/packets/game/clientbound_update_advancements_packet.rs4
-rw-r--r--azalea-protocol/src/packets/game/clientbound_update_attributes_packet.rs6
-rw-r--r--azalea-protocol/src/packets/game/clientbound_update_recipes_packet.rs6
-rwxr-xr-xazalea-protocol/src/packets/game/clientbound_update_tags_packet.rs6
-rwxr-xr-xazalea-protocol/src/packets/login/clientbound_game_profile_packet.rs29
-rwxr-xr-xazalea-protocol/src/packets/login/clientbound_login_compression_packet.rs4
-rw-r--r--azalea-protocol/src/packets/login/serverbound_key_packet.rs4
-rw-r--r--azalea-protocol/src/packets/mod.rs11
-rwxr-xr-xazalea-protocol/src/packets/status/clientbound_status_response_packet.rs11
-rwxr-xr-xazalea-protocol/src/read.rs118
-rwxr-xr-xazalea-protocol/src/resolver.rs20
-rwxr-xr-xazalea-protocol/src/write.rs63
-rw-r--r--azalea-world/Cargo.toml1
-rw-r--r--azalea-world/src/chunk.rs16
-rw-r--r--azalea-world/src/lib.rs22
-rw-r--r--azalea-world/src/palette.rs10
55 files changed, 589 insertions, 382 deletions
diff --git a/Cargo.lock b/Cargo.lock
index d38f8eaf..5f1bdb2e 100755
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -20,6 +20,12 @@ dependencies = [
]
[[package]]
+name = "anyhow"
+version = "1.0.59"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c91f1f46651137be86f3a2b9a8359f9ab421d04d941c62b5982e1ca21113adf9"
+
+[[package]]
name = "async-compression"
version = "0.3.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -75,6 +81,7 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
name = "azalea-auth"
version = "0.1.0"
dependencies = [
+ "azalea-buf",
"uuid",
]
@@ -95,6 +102,8 @@ version = "0.1.0"
dependencies = [
"buf-macros",
"byteorder",
+ "serde_json",
+ "thiserror",
"tokio",
"uuid",
]
@@ -114,12 +123,14 @@ dependencies = [
name = "azalea-client"
version = "0.1.0"
dependencies = [
+ "anyhow",
"azalea-auth",
"azalea-core",
"azalea-crypto",
"azalea-entity",
"azalea-protocol",
"azalea-world",
+ "thiserror",
"tokio",
"uuid",
]
@@ -218,6 +229,7 @@ dependencies = [
"azalea-nbt",
"log",
"nohash-hasher",
+ "thiserror",
"uuid",
]
@@ -1290,18 +1302,18 @@ dependencies = [
[[package]]
name = "thiserror"
-version = "1.0.31"
+version = "1.0.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bd829fe32373d27f76265620b5309d0340cb8550f523c1dda251d6298069069a"
+checksum = "f5f6586b7f764adc0231f4c79be7b920e766bb2f3e51b3661cdb263828f19994"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
-version = "1.0.31"
+version = "1.0.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0396bc89e626244658bef819e22d0cc459e795a5ebe878e6ec336d1674a8d79a"
+checksum = "12bafc5b54507e0149cdf1b145a5d80ab80a90bcd9275df43d4fff68460f6c21"
dependencies = [
"proc-macro2",
"quote",
diff --git a/azalea-auth/Cargo.toml b/azalea-auth/Cargo.toml
index fe306186..1bef8c57 100755
--- a/azalea-auth/Cargo.toml
+++ b/azalea-auth/Cargo.toml
@@ -6,4 +6,5 @@ version = "0.1.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
+azalea-buf = {path = "../azalea-buf"}
uuid = "1.1.2"
diff --git a/azalea-auth/src/game_profile.rs b/azalea-auth/src/game_profile.rs
index d75f60a4..333f926f 100755
--- a/azalea-auth/src/game_profile.rs
+++ b/azalea-auth/src/game_profile.rs
@@ -1,12 +1,12 @@
+use azalea_buf::McBuf;
use std::collections::HashMap;
-
use uuid::Uuid;
-#[derive(Clone, Debug)]
+#[derive(McBuf, Debug, Clone)]
pub struct GameProfile {
pub uuid: Uuid,
pub name: String,
- pub properties: HashMap<String, String>,
+ pub properties: HashMap<String, ProfilePropertyValue>,
}
impl GameProfile {
@@ -18,3 +18,9 @@ impl GameProfile {
}
}
}
+
+#[derive(McBuf, Debug, Clone)]
+pub struct ProfilePropertyValue {
+ pub value: String,
+ pub signature: Option<String>,
+}
diff --git a/azalea-buf/Cargo.toml b/azalea-buf/Cargo.toml
index 4321dace..0ff100ac 100644
--- a/azalea-buf/Cargo.toml
+++ b/azalea-buf/Cargo.toml
@@ -7,6 +7,11 @@ version = "0.1.0"
[dependencies]
buf-macros = {path = "./buf-macros"}
-byteorder = "1.4.3"
+byteorder = "^1.4.3"
+serde_json = {version = "^1.0", optional = true}
+thiserror = "^1.0.31"
tokio = {version = "^1.19.2", features = ["io-util", "net", "macros"]}
-uuid = "1.1.2"
+uuid = "^1.1.2"
+
+[features]
+serde_json = ["dep:serde_json"]
diff --git a/azalea-buf/buf-macros/Cargo.toml b/azalea-buf/buf-macros/Cargo.toml
index fecf64ed..64e9a228 100644
--- a/azalea-buf/buf-macros/Cargo.toml
+++ b/azalea-buf/buf-macros/Cargo.toml
@@ -10,4 +10,4 @@ proc-macro = true
[dependencies]
proc-macro2 = "^1.0.36"
quote = "^1.0.10"
-syn = "^1.0.82"
+syn = {version = "^1.0.82", features = ["extra-traits"]}
diff --git a/azalea-buf/buf-macros/src/lib.rs b/azalea-buf/buf-macros/src/lib.rs
index a735a920..25bceef0 100644
--- a/azalea-buf/buf-macros/src/lib.rs
+++ b/azalea-buf/buf-macros/src/lib.rs
@@ -41,7 +41,7 @@ fn create_impl_mcbufreadable(ident: &Ident, data: &Data) -> proc_macro2::TokenSt
quote! {
impl azalea_buf::McBufReadable for #ident {
- fn read_from(buf: &mut impl std::io::Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl std::io::Read) -> Result<Self, azalea_buf::BufReadError> {
#(#read_fields)*
Ok(#ident {
#(#read_field_names: #read_field_names),*
@@ -60,9 +60,14 @@ fn create_impl_mcbufreadable(ident: &Ident, data: &Data) -> proc_macro2::TokenSt
variant_discrim = match &d.1 {
syn::Expr::Lit(e) => match &e.lit {
syn::Lit::Int(i) => i.base10_parse().unwrap(),
- _ => panic!("Error parsing enum discriminant"),
+ _ => panic!("Error parsing enum discriminant as int"),
},
- _ => panic!("Error parsing enum discriminant"),
+ syn::Expr::Unary(_) => {
+ panic!("Negative enum discriminants are not supported")
+ }
+ _ => {
+ panic!("Error parsing enum discriminant as literal (is {:?})", d.1)
+ }
}
}
None => {
@@ -76,12 +81,12 @@ fn create_impl_mcbufreadable(ident: &Ident, data: &Data) -> proc_macro2::TokenSt
quote! {
impl azalea_buf::McBufReadable for #ident {
- fn read_from(buf: &mut impl std::io::Read) -> Result<Self, String>
+ fn read_from(buf: &mut impl std::io::Read) -> Result<Self, azalea_buf::BufReadError>
{
let id = azalea_buf::McBufVarReadable::var_read_from(buf)?;
match id {
#match_contents
- _ => Err(format!("Unknown enum variant {}", id)),
+ _ => Err(azalea_buf::BufReadError::UnexpectedEnumVariant { id: id as i32 }),
}
}
}
diff --git a/azalea-buf/src/definitions.rs b/azalea-buf/src/definitions.rs
index f3452bea..cfe1bd8a 100644
--- a/azalea-buf/src/definitions.rs
+++ b/azalea-buf/src/definitions.rs
@@ -1,4 +1,4 @@
-use crate::{McBufReadable, McBufWritable};
+use crate::{read::BufReadError, McBufReadable, McBufWritable};
use std::{
io::{Read, Write},
ops::Deref,
@@ -42,7 +42,7 @@ impl BitSet {
}
impl McBufReadable for BitSet {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
Ok(Self {
data: Vec::<u64>::read_from(buf)?,
})
diff --git a/azalea-buf/src/lib.rs b/azalea-buf/src/lib.rs
index 5bde833c..7860325e 100644
--- a/azalea-buf/src/lib.rs
+++ b/azalea-buf/src/lib.rs
@@ -9,7 +9,7 @@ mod write;
pub use buf_macros::*;
pub use definitions::*;
-pub use read::{read_varint_async, McBufReadable, McBufVarReadable, Readable};
+pub use read::{read_varint_async, BufReadError, McBufReadable, McBufVarReadable, Readable};
pub use serializable_uuid::*;
pub use write::{McBufVarWritable, McBufWritable, Writable};
diff --git a/azalea-buf/src/read.rs b/azalea-buf/src/read.rs
index 684404bc..8518d637 100644
--- a/azalea-buf/src/read.rs
+++ b/azalea-buf/src/read.rs
@@ -1,34 +1,62 @@
use super::{UnsizedByteArray, MAX_STRING_LENGTH};
use byteorder::{ReadBytesExt, BE};
use std::{collections::HashMap, hash::Hash, io::Read};
+use thiserror::Error;
use tokio::io::{AsyncRead, AsyncReadExt};
+#[derive(Error, Debug)]
+pub enum BufReadError {
+ #[error("Invalid VarInt")]
+ InvalidVarInt,
+ #[error("Invalid VarLong")]
+ InvalidVarLong,
+ #[error("Error reading bytes")]
+ CouldNotReadBytes,
+ #[error("The received encoded string buffer length is less than zero! Weird string!")]
+ StringLengthLessThanZero,
+ #[error("The received encoded string buffer length is longer than maximum allowed ({length} > {max_length})")]
+ StringLengthTooLong { length: i32, max_length: u32 },
+ #[error("{0}")]
+ Io(#[from] std::io::Error),
+ #[error("Boolean value is not 0 or 1")]
+ InvalidBoolean,
+ #[error("Invalid UTF-8")]
+ InvalidUtf8,
+ #[error("Unexpected enum variant {id}")]
+ UnexpectedEnumVariant { id: i32 },
+ #[error("{0}")]
+ Custom(String),
+ #[cfg(feature = "serde_json")]
+ #[error("{0}")]
+ Deserialization(#[from] serde_json::Error),
+}
+
// TODO: get rid of Readable and use McBufReadable everywhere
pub trait Readable {
- fn read_int_id_list(&mut self) -> Result<Vec<i32>, String>;
- fn read_varint(&mut self) -> Result<i32, String>;
+ fn read_int_id_list(&mut self) -> Result<Vec<i32>, BufReadError>;
+ fn read_varint(&mut self) -> Result<i32, BufReadError>;
fn get_varint_size(&mut self, value: i32) -> u8;
fn get_varlong_size(&mut self, value: i32) -> u8;
- fn read_byte_array(&mut self) -> Result<Vec<u8>, String>;
- fn read_bytes_with_len(&mut self, n: usize) -> Result<Vec<u8>, String>;
- fn read_bytes(&mut self) -> Result<Vec<u8>, String>;
- fn read_utf(&mut self) -> Result<String, String>;
- fn read_utf_with_len(&mut self, max_length: u32) -> Result<String, String>;
- fn read_byte(&mut self) -> Result<u8, String>;
- fn read_int(&mut self) -> Result<i32, String>;
- fn read_boolean(&mut self) -> Result<bool, String>;
- fn read_long(&mut self) -> Result<i64, String>;
- fn read_short(&mut self) -> Result<i16, String>;
- fn read_float(&mut self) -> Result<f32, String>;
- fn read_double(&mut self) -> Result<f64, String>;
+ fn read_byte_array(&mut self) -> Result<Vec<u8>, BufReadError>;
+ fn read_bytes_with_len(&mut self, n: usize) -> Result<Vec<u8>, BufReadError>;
+ fn read_bytes(&mut self) -> Result<Vec<u8>, BufReadError>;
+ fn read_utf(&mut self) -> Result<String, BufReadError>;
+ fn read_utf_with_len(&mut self, max_length: u32) -> Result<String, BufReadError>;
+ fn read_byte(&mut self) -> Result<u8, BufReadError>;
+ fn read_int(&mut self) -> Result<i32, BufReadError>;
+ fn read_boolean(&mut self) -> Result<bool, BufReadError>;
+ fn read_long(&mut self) -> Result<i64, BufReadError>;
+ fn read_short(&mut self) -> Result<i16, BufReadError>;
+ fn read_float(&mut self) -> Result<f32, BufReadError>;
+ fn read_double(&mut self) -> Result<f64, BufReadError>;
}
impl<R> Readable for R
where
R: Read,
{
- fn read_int_id_list(&mut self) -> Result<Vec<i32>, String> {
+ fn read_int_id_list(&mut self) -> Result<Vec<i32>, BufReadError> {
let len = self.read_varint()?;
let mut list = Vec::with_capacity(len as usize);
for _ in 0..len {
@@ -39,12 +67,12 @@ where
// fast varints modified from https://github.com/luojia65/mc-varint/blob/master/src/lib.rs#L67
/// Read a single varint from the reader and return the value, along with the number of bytes read
- fn read_varint(&mut self) -> Result<i32, String> {
+ fn read_varint(&mut self) -> Result<i32, BufReadError> {
let mut buffer = [0];
let mut ans = 0;
for i in 0..5 {
self.read_exact(&mut buffer)
- .map_err(|_| "Invalid VarInt".to_string())?;
+ .map_err(|_| BufReadError::InvalidVarInt)?;
ans |= ((buffer[0] & 0b0111_1111) as i32) << (7 * i);
if buffer[0] & 0b1000_0000 == 0 {
return Ok(ans);
@@ -73,122 +101,102 @@ where
10
}
- fn read_byte_array(&mut self) -> Result<Vec<u8>, String> {
+ fn read_byte_array(&mut self) -> Result<Vec<u8>, BufReadError> {
let length = self.read_varint()? as usize;
self.read_bytes_with_len(length)
}
- fn read_bytes_with_len(&mut self, n: usize) -> Result<Vec<u8>, String> {
+ fn read_bytes_with_len(&mut self, n: usize) -> Result<Vec<u8>, BufReadError> {
let mut buffer = vec![0; n];
self.read_exact(&mut buffer)
- .map_err(|_| "Error reading bytes".to_string())?;
+ .map_err(|_| BufReadError::CouldNotReadBytes)?;
Ok(buffer)
}
- fn read_bytes(&mut self) -> Result<Vec<u8>, String> {
+ fn read_bytes(&mut self) -> Result<Vec<u8>, BufReadError> {
// read to end of the buffer
let mut bytes = vec![];
self.read_to_end(&mut bytes)
- .map_err(|_| "Error reading bytes".to_string())?;
+ .map_err(|_| BufReadError::CouldNotReadBytes)?;
Ok(bytes)
}
- fn read_utf(&mut self) -> Result<String, String> {
+ fn read_utf(&mut self) -> Result<String, BufReadError> {
self.read_utf_with_len(MAX_STRING_LENGTH.into())
}
- fn read_utf_with_len(&mut self, max_length: u32) -> Result<String, String> {
+ fn read_utf_with_len(&mut self, max_length: u32) -> Result<String, BufReadError> {
let length = self.read_varint()?;
// i don't know why it's multiplied by 4 but it's like that in mojang's code so
if length < 0 {
- return Err(
- "The received encoded string buffer length is less than zero! Weird string!"
- .to_string(),
- );
+ return Err(BufReadError::StringLengthLessThanZero);
}
if length as u32 > max_length * 4 {
- return Err(format!(
- "The received encoded string buffer length is longer than maximum allowed ({} > {})",
+ return Err(BufReadError::StringLengthTooLong {
length,
- max_length * 4
- ));
+ max_length: max_length * 4,
+ });
}
// this is probably quite inefficient, idk how to do it better
let mut string = String::new();
let mut buffer = vec![0; length as usize];
self.read_exact(&mut buffer)
- .map_err(|_| "Invalid UTF-8".to_string())?;
+ .map_err(|_| BufReadError::InvalidUtf8)?;
string.push_str(std::str::from_utf8(&buffer).unwrap());
if string.len() > length as usize {
- return Err(format!(
- "The received string length is longer than maximum allowed ({} > {})",
- length, max_length
- ));
+ return Err(BufReadError::StringLengthTooLong { length, max_length });
}
Ok(string)
}
/// Read a single byte from the reader
- fn read_byte(&mut self) -> Result<u8, String> {
- self.read_u8().map_err(|_| "Error reading byte".to_string())
+ fn read_byte(&mut self) -> Result<u8, BufReadError> {
+ Ok(self.read_u8()?)
}
- fn read_int(&mut self) -> Result<i32, String> {
- match self.read_i32::<BE>() {
- Ok(r) => Ok(r),
- Err(_) => Err("Error reading int".to_string()),
- }
+ fn read_int(&mut self) -> Result<i32, BufReadError> {
+ Ok(self.read_i32::<BE>()?)
}
- fn read_boolean(&mut self) -> Result<bool, String> {
+ fn read_boolean(&mut self) -> Result<bool, BufReadError> {
match self.read_byte()? {
0 => Ok(false),
1 => Ok(true),
- _ => Err("Error reading boolean".to_string()),
+ _ => Err(BufReadError::InvalidBoolean),
}
}
- fn read_long(&mut self) -> Result<i64, String> {
- match self.read_i64::<BE>() {
- Ok(r) => Ok(r),
- Err(_) => Err("Error reading long".to_string()),
- }
+ fn read_long(&mut self) -> Result<i64, BufReadError> {
+ Ok(self.read_i64::<BE>()?)
}
- fn read_short(&mut self) -> Result<i16, String> {
- match self.read_i16::<BE>() {
- Ok(r) => Ok(r),
- Err(_) => Err("Error reading short".to_string()),
- }
+ fn read_short(&mut self) -> Result<i16, BufReadError> {
+ Ok(self.read_i16::<BE>()?)
}
- fn read_float(&mut self) -> Result<f32, String> {
- match self.read_f32::<BE>() {
- Ok(r) => Ok(r),
- Err(_) => Err("Error reading float".to_string()),
- }
+ fn read_float(&mut self) -> Result<f32, BufReadError> {
+ Ok(self.read_f32::<BE>()?)
}
- fn read_double(&mut self) -> Result<f64, String> {
- match self.read_f64::<BE>() {
- Ok(r) => Ok(r),
- Err(_) => Err("Error reading double".to_string()),
- }
+ fn read_double(&mut self) -> Result<f64, BufReadError> {
+ Ok(self.read_f64::<BE>()?)
}
}
// fast varints modified from https://github.com/luojia65/mc-varint/blob/master/src/lib.rs#L67
/// Read a single varint from the reader and return the value, along with the number of bytes read
-pub async fn read_varint_async(reader: &mut (dyn AsyncRead + Unpin + Send)) -> Result<i32, String> {
+pub async fn read_varint_async(
+ reader: &mut (dyn AsyncRead + Unpin + Send),
+) -> Result<i32, BufReadError> {
let mut buffer = [0];
let mut ans = 0;
for i in 0..5 {
reader
.read_exact(&mut buffer)
.await
- .map_err(|_| "Invalid VarInt".to_string())?;
+ .map_err(|_| BufReadError::InvalidVarInt)?;
ans |= ((buffer[0] & 0b0111_1111) as i32) << (7 * i);
if buffer[0] & 0b1000_0000 == 0 {
return Ok(ans);
@@ -201,36 +209,36 @@ pub trait McBufReadable
where
Self: Sized,
{
- fn read_from(buf: &mut impl Read) -> Result<Self, String>;
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError>;
}
pub trait McBufVarReadable
where
Self: Sized,
{
- fn var_read_from(buf: &mut impl Read) -> Result<Self, String>;
+ fn var_read_from(buf: &mut impl Read) -> Result<Self, BufReadError>;
}
impl McBufReadable for i32 {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
Readable::read_int(buf)
}
}
impl McBufVarReadable for i32 {
- fn var_read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn var_read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
buf.read_varint()
}
}
impl McBufVarReadable for i64 {
// fast varints modified from https://github.com/luojia65/mc-varint/blob/master/src/lib.rs#L54
- fn var_read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn var_read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
let mut buffer = [0];
let mut ans = 0;
for i in 0..8 {
buf.read_exact(&mut buffer)
- .map_err(|_| "Invalid VarLong".to_string())?;
+ .map_err(|_| BufReadError::InvalidVarLong)?;
ans |= ((buffer[0] & 0b0111_1111) as i64) << (7 * i);
if buffer[0] & 0b1000_0000 == 0 {
break;
@@ -240,19 +248,19 @@ impl McBufVarReadable for i64 {
}
}
impl McBufVarReadable for u64 {
- fn var_read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn var_read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
i64::var_read_from(buf).map(|i| i as u64)
}
}
impl McBufReadable for UnsizedByteArray {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
Ok(buf.read_bytes()?.into())
}
}
impl<T: McBufReadable + Send> McBufReadable for Vec<T> {
- default fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ default fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
let length = buf.read_varint()? as usize;
let mut contents = Vec::with_capacity(length);
for _ in 0..length {
@@ -263,7 +271,7 @@ impl<T: McBufReadable + Send> McBufReadable for Vec<T> {
}
impl<K: McBufReadable + Send + Eq + Hash, V: McBufReadable + Send> McBufReadable for HashMap<K, V> {
- default fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ default fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
let length = buf.read_varint()? as usize;
let mut contents = HashMap::with_capacity(length);
for _ in 0..length {
@@ -274,49 +282,49 @@ impl<K: McBufReadable + Send + Eq + Hash, V: McBufReadable + Send> McBufReadable
}
impl McBufReadable for Vec<u8> {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
buf.read_byte_array()
}
}
impl McBufReadable for String {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
buf.read_utf()
}
}
impl McBufReadable for u32 {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
Readable::read_int(buf).map(|i| i as u32)
}
}
impl McBufVarReadable for u32 {
- fn var_read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn var_read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
buf.read_varint().map(|i| i as u32)
}
}
impl McBufReadable for u16 {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
buf.read_short().map(|i| i as u16)
}
}
impl McBufReadable for i16 {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
buf.read_short()
}
}
impl McBufVarReadable for u16 {
- fn var_read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn var_read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
buf.read_varint().map(|i| i as u16)
}
}
impl<T: McBufVarReadable> McBufVarReadable for Vec<T> {
- fn var_read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn var_read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
let length = buf.read_varint()? as usize;
let mut contents = Vec::with_capacity(length);
for _ in 0..length {
@@ -327,49 +335,49 @@ impl<T: McBufVarReadable> McBufVarReadable for Vec<T> {
}
impl McBufReadable for i64 {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
buf.read_long()
}
}
impl McBufReadable for u64 {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
i64::read_from(buf).map(|i| i as u64)
}
}
impl McBufReadable for bool {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
buf.read_boolean()
}
}
impl McBufReadable for u8 {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
buf.read_byte()
}
}
impl McBufReadable for i8 {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
buf.read_byte().map(|i| i as i8)
}
}
impl McBufReadable for f32 {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
buf.read_float()
}
}
impl McBufReadable for f64 {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
buf.read_double()
}
}
impl<T: McBufReadable> McBufReadable for Option<T> {
- default fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ default fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
let present = buf.read_boolean()?;
Ok(if present {
Some(T::read_from(buf)?)
diff --git a/azalea-buf/src/serializable_uuid.rs b/azalea-buf/src/serializable_uuid.rs
index eb256d90..fad5edfc 100644
--- a/azalea-buf/src/serializable_uuid.rs
+++ b/azalea-buf/src/serializable_uuid.rs
@@ -1,4 +1,4 @@
-use crate::{McBufReadable, McBufWritable, Readable};
+use crate::{read::BufReadError, McBufReadable, McBufWritable, Readable};
use std::io::{Read, Write};
use uuid::Uuid;
@@ -33,7 +33,7 @@ impl SerializableUuid for Uuid {
}
impl McBufReadable for Uuid {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
Ok(Uuid::from_int_array([
Readable::read_int(buf)? as u32,
Readable::read_int(buf)? as u32,
diff --git a/azalea-chat/Cargo.toml b/azalea-chat/Cargo.toml
index 5b85f6c2..2da86829 100755
--- a/azalea-chat/Cargo.toml
+++ b/azalea-chat/Cargo.toml
@@ -6,7 +6,7 @@ version = "0.1.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
-azalea-buf = {path = "../azalea-buf"}
+azalea-buf = {path = "../azalea-buf", features = ["serde_json"]}
azalea-language = {path = "../azalea-language"}
lazy_static = "1.4.0"
serde = "^1.0.130"
diff --git a/azalea-chat/src/component.rs b/azalea-chat/src/component.rs
index d2f687d4..8a038bf0 100755
--- a/azalea-chat/src/component.rs
+++ b/azalea-chat/src/component.rs
@@ -1,6 +1,6 @@
use std::io::{Read, Write};
-use azalea_buf::{McBufReadable, McBufWritable};
+use azalea_buf::{BufReadError, McBufReadable, McBufWritable};
use serde::{de, Deserialize, Deserializer};
use crate::{
@@ -269,11 +269,10 @@ impl<'de> Deserialize<'de> for Component {
}
impl McBufReadable for Component {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
let string = String::read_from(buf)?;
- let json: serde_json::Value = serde_json::from_str(string.as_str())
- .map_err(|_| "Component isn't valid JSON".to_string())?;
- let component = Component::deserialize(json).map_err(|e| e.to_string())?;
+ let json: serde_json::Value = serde_json::from_str(string.as_str())?;
+ let component = Component::deserialize(json)?;
Ok(component)
}
}
diff --git a/azalea-chat/src/style.rs b/azalea-chat/src/style.rs
index 9fca6563..3a667776 100755
--- a/azalea-chat/src/style.rs
+++ b/azalea-chat/src/style.rs
@@ -9,17 +9,17 @@ pub struct TextColor {
}
impl TextColor {
- pub fn parse(value: String) -> Result<TextColor, String> {
+ pub fn parse(value: String) -> Option<TextColor> {
if value.starts_with('#') {
let n = value.chars().skip(1).collect::<String>();
let n = u32::from_str_radix(&n, 16).unwrap();
- return Ok(TextColor::from_rgb(n));
+ return Some(TextColor::from_rgb(n));
}
let color_option = NAMED_COLORS.get(&value.to_ascii_uppercase());
if let Some(color) = color_option {
- return Ok(color.clone());
+ return Some(color.clone());
}
- Err(format!("Invalid color {}", value))
+ None
}
fn from_rgb(value: u32) -> TextColor {
@@ -157,13 +157,14 @@ impl<'a> ChatFormatting<'a> {
}
}
- pub fn from_code(code: char) -> Result<&'static ChatFormatting<'static>, String> {
+ pub fn from_code(code: char) -> Option<&'static ChatFormatting<'static>> {
for formatter in &ChatFormatting::FORMATTERS {
if formatter.code == code {
- return Ok(formatter);
+ return Some(formatter);
}
}
- Err(format!("Invalid formatting code {}", code))
+
+ None
}
}
@@ -241,7 +242,7 @@ impl Style {
let color: Option<TextColor> = json_object
.get("color")
.and_then(|v| v.as_str())
- .and_then(|v| TextColor::parse(v.to_string()).ok());
+ .and_then(|v| TextColor::parse(v.to_string()));
Style {
color,
bold,
diff --git a/azalea-chat/src/text_component.rs b/azalea-chat/src/text_component.rs
index a704f455..a3eb0e4b 100755
--- a/azalea-chat/src/text_component.rs
+++ b/azalea-chat/src/text_component.rs
@@ -22,7 +22,7 @@ pub fn legacy_color_code_to_text_component(legacy_color_code: &str) -> TextCompo
while i < legacy_color_code.chars().count() {
if legacy_color_code.chars().nth(i).unwrap() == LEGACY_FORMATTING_CODE_SYMBOL {
let formatting_code = legacy_color_code.chars().nth(i + 1).unwrap();
- if let Ok(formatter) = ChatFormatting::from_code(formatting_code) {
+ if let Some(formatter) = ChatFormatting::from_code(formatting_code) {
if components.is_empty() || !components.last().unwrap().text.is_empty() {
components.push(TextComponent::new("".to_string()));
}
diff --git a/azalea-client/Cargo.toml b/azalea-client/Cargo.toml
index dc340812..50ba09e2 100755
--- a/azalea-client/Cargo.toml
+++ b/azalea-client/Cargo.toml
@@ -6,11 +6,13 @@ version = "0.1.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
+anyhow = "1.0.59"
azalea-auth = {path = "../azalea-auth"}
azalea-core = {path = "../azalea-core"}
azalea-crypto = {path = "../azalea-crypto"}
azalea-entity = {path = "../azalea-entity"}
azalea-protocol = {path = "../azalea-protocol"}
azalea-world = {path = "../azalea-world"}
-tokio = {version = "1.19.2", features = ["sync"]}
-uuid = "1.1.2"
+thiserror = "^1.0.32"
+tokio = {version = "^1.19.2", features = ["sync"]}
+uuid = "^1.1.2"
diff --git a/azalea-client/src/account.rs b/azalea-client/src/account.rs
index 32a46406..c554908f 100644
--- a/azalea-client/src/account.rs
+++ b/azalea-client/src/account.rs
@@ -1,6 +1,6 @@
//! Connect to Minecraft servers.
-use crate::{Client, Event};
+use crate::{client::JoinError, Client, Event};
use azalea_protocol::ServerAddress;
use tokio::sync::mpsc::UnboundedReceiver;
@@ -19,7 +19,7 @@ impl Account {
pub async fn join(
&self,
address: &ServerAddress,
- ) -> Result<(Client, UnboundedReceiver<Event>), String> {
+ ) -> Result<(Client, UnboundedReceiver<Event>), JoinError> {
Client::join(self, address).await
}
}
diff --git a/azalea-client/src/client.rs b/azalea-client/src/client.rs
index 28154bce..38e36b63 100644
--- a/azalea-client/src/client.rs
+++ b/azalea-client/src/client.rs
@@ -3,7 +3,7 @@ use azalea_auth::game_profile::GameProfile;
use azalea_core::{ChunkPos, EntityPos, PositionDelta, PositionDeltaTrait, ResourceLocation};
use azalea_entity::Entity;
use azalea_protocol::{
- connect::Connection,
+ connect::{Connection, ConnectionError},
packets::{
game::{
clientbound_player_chat_packet::ClientboundPlayerChatPacket,
@@ -22,13 +22,16 @@ use azalea_protocol::{
},
ConnectionProtocol, PROTOCOL_VERSION,
},
+ read::ReadPacketError,
resolver, ServerAddress,
};
use azalea_world::Dimension;
use std::{
fmt::Debug,
+ io,
sync::{Arc, Mutex},
};
+use thiserror::Error;
use tokio::{
sync::mpsc::{self, UnboundedReceiver, UnboundedSender},
time::{self},
@@ -70,15 +73,34 @@ pub struct Client {
/// Whether we should ignore errors when decoding packets.
const IGNORE_ERRORS: bool = !cfg!(debug_assertions);
-#[derive(Debug)]
-struct HandleError(String);
+#[derive(Error, Debug)]
+pub enum JoinError {
+ #[error("{0}")]
+ Resolver(#[from] resolver::ResolverError),
+ #[error("{0}")]
+ Connection(#[from] ConnectionError),
+ #[error("{0}")]
+ ReadPacket(#[from] azalea_protocol::read::ReadPacketError),
+ #[error("{0}")]
+ Io(#[from] io::Error),
+}
+
+#[derive(Error, Debug)]
+pub enum HandleError {
+ #[error("{0}")]
+ Poison(String),
+ #[error("{0}")]
+ Io(#[from] io::Error),
+ #[error(transparent)]
+ Other(#[from] anyhow::Error),
+}
impl Client {
/// Connect to a Minecraft server with an account.
pub async fn join(
account: &Account,
address: &ServerAddress,
- ) -> Result<(Self, UnboundedReceiver<Event>), String> {
+ ) -> Result<(Self, UnboundedReceiver<Event>), JoinError> {
let resolved_address = resolver::resolve_address(address).await?;
let mut conn = Connection::new(&resolved_address).await?;
@@ -93,7 +115,7 @@ impl Client {
}
.get(),
)
- .await;
+ .await?;
let mut conn = conn.login();
// login
@@ -105,7 +127,7 @@ impl Client {
}
.get(),
)
- .await;
+ .await?;
let (conn, game_profile) = loop {
let packet_result = conn.read().await;
@@ -126,7 +148,7 @@ impl Client {
}
.get(),
)
- .await;
+ .await?;
conn.set_encryption_key(e.secret_key);
}
ClientboundLoginPacket::ClientboundLoginCompressionPacket(p) => {
@@ -180,22 +202,23 @@ impl Client {
Ok(packet) => match Self::handle(&packet, &client, &tx).await {
Ok(_) => {}
Err(e) => {
- println!("Error handling packet: {:?}", e);
+ println!("Error handling packet: {}", e);
if IGNORE_ERRORS {
continue;
} else {
- panic!("Error handling packet: {:?}", e);
+ panic!("Error handling packet: {}", e);
}
}
},
Err(e) => {
if IGNORE_ERRORS {
- println!("Error: {:?}", e);
- if e == "length wider than 21-bit" {
- panic!();
+ println!("{}", e);
+ match e {
+ ReadPacketError::FrameSplitter { .. } => panic!("Error: {:?}", e),
+ _ => continue,
}
} else {
- panic!("Error: {:?}", e);
+ panic!("{}", e);
}
}
};
@@ -303,7 +326,7 @@ impl Client {
}
.get(),
)
- .await;
+ .await?;
tx.send(Event::Login).unwrap();
}
@@ -416,7 +439,7 @@ impl Client {
let mut conn_lock = client.conn.lock().await;
conn_lock
.write(ServerboundAcceptTeleportationPacket { id: p.id }.get())
- .await;
+ .await?;
conn_lock
.write(
ServerboundMovePlayerPacketPosRot {
@@ -430,7 +453,7 @@ impl Client {
}
.get(),
)
- .await;
+ .await?;
}
ClientboundGamePacket::ClientboundPlayerInfoPacket(p) => {
println!("Got player info packet {:?}", p);
@@ -514,14 +537,16 @@ impl Client {
let mut dimension_lock = client.dimension.lock()?;
let dimension = dimension_lock.as_mut().unwrap();
- dimension.move_entity(
- p.id,
- EntityPos {
- x: p.x,
- y: p.y,
- z: p.z,
- },
- )?;
+ dimension
+ .move_entity(
+ p.id,
+ EntityPos {
+ x: p.x,
+ y: p.y,
+ z: p.z,
+ },
+ )
+ .map_err(|e| HandleError::Other(e.into()))?;
}
ClientboundGamePacket::ClientboundUpdateAdvancementsPacket(p) => {
println!("Got update advancements packet {:?}", p);
@@ -533,13 +558,17 @@ impl Client {
let mut dimension_lock = client.dimension.lock()?;
let dimension = dimension_lock.as_mut().unwrap();
- dimension.move_entity_with_delta(p.entity_id, &p.delta)?;
+ dimension
+ .move_entity_with_delta(p.entity_id, &p.delta)
+ .map_err(|e| HandleError::Other(e.into()))?;
}
ClientboundGamePacket::ClientboundMoveEntityPosrotPacket(p) => {
let mut dimension_lock = client.dimension.lock()?;
let dimension = dimension_lock.as_mut().unwrap();
- dimension.move_entity_with_delta(p.entity_id, &p.delta)?;
+ dimension
+ .move_entity_with_delta(p.entity_id, &p.delta)
+ .map_err(|e| HandleError::Other(e.into()))?;
}
ClientboundGamePacket::ClientboundMoveEntityRotPacket(p) => {
println!("Got move entity rot packet {:?}", p);
@@ -551,7 +580,7 @@ impl Client {
.lock()
.await
.write(ServerboundKeepAlivePacket { id: p.id }.get())
- .await;
+ .await?;
}
ClientboundGamePacket::ClientboundRemoveEntitiesPacket(p) => {
println!("Got remove entities packet {:?}", p);
@@ -625,12 +654,6 @@ impl Client {
impl<T> From<std::sync::PoisonError<T>> for HandleError {
fn from(e: std::sync::PoisonError<T>) -> Self {
- HandleError(e.to_string())
- }
-}
-
-impl From<String> for HandleError {
- fn from(e: String) -> Self {
- HandleError(e)
+ HandleError::Poison(e.to_string())
}
}
diff --git a/azalea-client/src/movement.rs b/azalea-client/src/movement.rs
index 4f99984f..bc48e1b2 100644
--- a/azalea-client/src/movement.rs
+++ b/azalea-client/src/movement.rs
@@ -1,10 +1,20 @@
use crate::Client;
use azalea_core::EntityPos;
use azalea_protocol::packets::game::serverbound_move_player_packet_pos_rot::ServerboundMovePlayerPacketPosRot;
+use azalea_world::MoveEntityError;
+use thiserror::Error;
+
+#[derive(Error, Debug)]
+pub enum MovePlayerError {
+ #[error("Player is not in world")]
+ PlayerNotInWorld,
+ #[error("{0}")]
+ Io(#[from] std::io::Error),
+}
impl Client {
/// Set the client's position to the given coordinates.
- pub async fn move_to(&mut self, new_pos: EntityPos) -> Result<(), String> {
+ pub async fn move_to(&mut self, new_pos: EntityPos) -> Result<(), MovePlayerError> {
{
let mut dimension_lock = self.dimension.lock().unwrap();
let dimension = dimension_lock.as_mut().unwrap();
@@ -14,10 +24,15 @@ impl Client {
let player_id = if let Some(player_lock) = player_lock.entity(dimension) {
player_lock.id
} else {
- return Err("Player entity not found".to_string());
+ return Err(MovePlayerError::PlayerNotInWorld);
};
- dimension.move_entity(player_id, new_pos)?;
+ match dimension.move_entity(player_id, new_pos) {
+ Ok(_) => Ok(()),
+ Err(e) => match e {
+ MoveEntityError::EntityDoesNotExist => Err(MovePlayerError::PlayerNotInWorld),
+ },
+ }?;
}
self.conn
@@ -34,7 +49,7 @@ impl Client {
}
.get(),
)
- .await;
+ .await?;
Ok(())
}
diff --git a/azalea-client/src/ping.rs b/azalea-client/src/ping.rs
index e4acfc34..303fae74 100755
--- a/azalea-client/src/ping.rs
+++ b/azalea-client/src/ping.rs
@@ -1,6 +1,6 @@
///! Ping Minecraft servers.
use azalea_protocol::{
- connect::Connection,
+ connect::{Connection, ConnectionError},
packets::{
handshake::client_intention_packet::ClientIntentionPacket,
status::{
@@ -12,10 +12,24 @@ use azalea_protocol::{
},
resolver, ServerAddress,
};
+use std::io;
+use thiserror::Error;
+
+#[derive(Error, Debug)]
+pub enum PingError {
+ #[error("{0}")]
+ Resolver(#[from] resolver::ResolverError),
+ #[error("{0}")]
+ Connection(#[from] ConnectionError),
+ #[error("{0}")]
+ ReadPacket(#[from] azalea_protocol::read::ReadPacketError),
+ #[error("{0}")]
+ WritePacket(#[from] io::Error),
+}
pub async fn ping_server(
address: &ServerAddress,
-) -> Result<ClientboundStatusResponsePacket, String> {
+) -> Result<ClientboundStatusResponsePacket, PingError> {
let resolved_address = resolver::resolve_address(address).await?;
let mut conn = Connection::new(&resolved_address).await?;
@@ -30,13 +44,13 @@ pub async fn ping_server(
}
.get(),
)
- .await;
+ .await?;
let mut conn = conn.status();
// send the empty status request packet
- conn.write(ServerboundStatusRequestPacket {}.get()).await;
+ conn.write(ServerboundStatusRequestPacket {}.get()).await?;
- let packet = conn.read().await.unwrap();
+ let packet = conn.read().await?;
match packet {
ClientboundStatusPacket::ClientboundStatusResponsePacket(p) => Ok(p),
diff --git a/azalea-core/src/difficulty.rs b/azalea-core/src/difficulty.rs
index f2877f79..65950e8d 100755
--- a/azalea-core/src/difficulty.rs
+++ b/azalea-core/src/difficulty.rs
@@ -3,7 +3,7 @@ use std::{
io::{Read, Write},
};
-use azalea_buf::{McBufReadable, McBufWritable};
+use azalea_buf::{BufReadError, McBufReadable, McBufWritable};
#[derive(Hash, Clone, Debug, PartialEq, Eq)]
pub enum Difficulty {
@@ -67,7 +67,7 @@ impl Difficulty {
}
impl McBufReadable for Difficulty {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
Ok(Difficulty::by_id(u8::read_from(buf)?))
}
}
diff --git a/azalea-core/src/game_type.rs b/azalea-core/src/game_type.rs
index d41e5b84..429af324 100755
--- a/azalea-core/src/game_type.rs
+++ b/azalea-core/src/game_type.rs
@@ -1,4 +1,4 @@
-use azalea_buf::{McBufReadable, McBufWritable};
+use azalea_buf::{BufReadError, McBufReadable, McBufWritable};
use std::io::{Read, Write};
#[derive(Hash, Copy, Clone, Debug)]
@@ -27,22 +27,24 @@ impl GameType {
}
}
- pub fn from_id(id: u8) -> Result<GameType, String> {
- Ok(match id {
+ pub fn from_id(id: u8) -> Option<GameType> {
+ Some(match id {
0 => GameType::SURVIVAL,
1 => GameType::CREATIVE,
2 => GameType::ADVENTURE,
3 => GameType::SPECTATOR,
- _ => return Err(format!("Unknown game type id: {}", id)),
+ _ => return None,
})
}
- pub fn from_optional_id(id: i8) -> Result<OptionalGameType, String> {
- Ok(match id {
- -1 => None,
- id => Some(GameType::from_id(id as u8)?),
- }
- .into())
+ pub fn from_optional_id(id: i8) -> Option<OptionalGameType> {
+ Some(
+ match id {
+ -1 => None,
+ id => Some(GameType::from_id(id as u8)?),
+ }
+ .into(),
+ )
}
pub fn short_name(&self) -> &'static str {
@@ -77,8 +79,9 @@ impl GameType {
}
impl McBufReadable for GameType {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
- GameType::from_id(u8::read_from(buf)?)
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
+ let id = u8::read_from(buf)?;
+ GameType::from_id(id).ok_or_else(|| BufReadError::UnexpectedEnumVariant { id: id as i32 })
}
}
@@ -105,8 +108,10 @@ impl From<OptionalGameType> for Option<GameType> {
}
impl McBufReadable for OptionalGameType {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
- GameType::from_optional_id(i8::read_from(buf)?)
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
+ let id = i8::read_from(buf)?;
+ GameType::from_optional_id(id)
+ .ok_or_else(|| BufReadError::UnexpectedEnumVariant { id: id as i32 })
}
}
diff --git a/azalea-core/src/particle/mod.rs b/azalea-core/src/particle/mod.rs
index 46f88407..c2fa3337 100644
--- a/azalea-core/src/particle/mod.rs
+++ b/azalea-core/src/particle/mod.rs
@@ -1,5 +1,5 @@
use crate::{BlockPos, Slot};
-use azalea_buf::{McBuf, McBufReadable, McBufVarReadable, McBufWritable};
+use azalea_buf::{BufReadError, McBuf, McBufReadable, McBufVarReadable, McBufWritable};
use std::io::{Read, Write};
#[derive(Debug, Clone, McBuf)]
@@ -153,7 +153,7 @@ pub struct VibrationParticle {
}
impl ParticleData {
- pub fn read_from_particle_id(buf: &mut impl Read, id: u32) -> Result<Self, String> {
+ pub fn read_from_particle_id(buf: &mut impl Read, id: u32) -> Result<Self, BufReadError> {
Ok(match id {
0 => ParticleData::AmbientEntityEffect,
1 => ParticleData::AngryVillager,
@@ -243,13 +243,13 @@ impl ParticleData {
85 => ParticleData::WaxOff,
86 => ParticleData::ElectricSpark,
87 => ParticleData::Scrape,
- _ => return Err(format!("Unknown particle id: {}", id)),
+ _ => return Err(BufReadError::UnexpectedEnumVariant { id: id as i32 }),
})
}
}
impl McBufReadable for ParticleData {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
let id = u32::var_read_from(buf)?;
ParticleData::read_from_particle_id(buf, id)
}
diff --git a/azalea-core/src/position.rs b/azalea-core/src/position.rs
index adc5cafa..7371d530 100644
--- a/azalea-core/src/position.rs
+++ b/azalea-core/src/position.rs
@@ -1,5 +1,5 @@
use crate::ResourceLocation;
-use azalea_buf::{McBufReadable, McBufWritable};
+use azalea_buf::{BufReadError, McBufReadable, McBufWritable};
use std::{
io::{Read, Write},
ops::Rem,
@@ -225,7 +225,7 @@ impl From<&EntityPos> for ChunkPos {
}
impl McBufReadable for BlockPos {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
let val = u64::read_from(buf)?;
let x = (val >> 38) as i32;
let y = (val & 0xFFF) as i32;
@@ -235,7 +235,7 @@ impl McBufReadable for BlockPos {
}
impl McBufReadable for GlobalPos {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
Ok(GlobalPos {
dimension: ResourceLocation::read_from(buf)?,
pos: BlockPos::read_from(buf)?,
@@ -244,7 +244,7 @@ impl McBufReadable for GlobalPos {
}
impl McBufReadable for ChunkSectionPos {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
let long = i64::read_from(buf)?;
Ok(ChunkSectionPos {
x: (long >> 42) as i32,
diff --git a/azalea-core/src/resource_location.rs b/azalea-core/src/resource_location.rs
index 945b6d80..4c0764e5 100755
--- a/azalea-core/src/resource_location.rs
+++ b/azalea-core/src/resource_location.rs
@@ -1,6 +1,6 @@
//! A resource, like minecraft:stone
-use azalea_buf::{McBufReadable, McBufWritable};
+use azalea_buf::{BufReadError, McBufReadable, McBufWritable};
use std::io::{Read, Write};
#[derive(Hash, Clone, PartialEq, Eq)]
@@ -13,7 +13,7 @@ static DEFAULT_NAMESPACE: &str = "minecraft";
// static REALMS_NAMESPACE: &str = "realms";
impl ResourceLocation {
- pub fn new(resource_string: &str) -> Result<ResourceLocation, String> {
+ pub fn new(resource_string: &str) -> Result<ResourceLocation, BufReadError> {
let sep_byte_position_option = resource_string.chars().position(|c| c == ':');
let (namespace, path) = if let Some(sep_byte_position) = sep_byte_position_option {
if sep_byte_position == 0 {
@@ -46,7 +46,7 @@ impl std::fmt::Debug for ResourceLocation {
}
impl McBufReadable for ResourceLocation {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
let location_string = String::read_from(buf)?;
ResourceLocation::new(&location_string)
}
diff --git a/azalea-core/src/slot.rs b/azalea-core/src/slot.rs
index 8b1f784d..38abcf61 100644
--- a/azalea-core/src/slot.rs
+++ b/azalea-core/src/slot.rs
@@ -1,6 +1,6 @@
// TODO: have an azalea-inventory or azalea-container crate and put this there
-use azalea_buf::{McBuf, McBufReadable, McBufWritable};
+use azalea_buf::{BufReadError, McBuf, McBufReadable, McBufWritable};
use std::io::{Read, Write};
#[derive(Debug, Clone)]
@@ -18,7 +18,7 @@ pub struct SlotData {
}
impl McBufReadable for Slot {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
let present = bool::read_from(buf)?;
if !present {
return Ok(Slot::Empty);
diff --git a/azalea-entity/src/data.rs b/azalea-entity/src/data.rs
index c9083893..ff708653 100644
--- a/azalea-entity/src/data.rs
+++ b/azalea-entity/src/data.rs
@@ -1,4 +1,4 @@
-use azalea_buf::McBufVarReadable;
+use azalea_buf::{BufReadError, McBufVarReadable};
use azalea_buf::{McBuf, McBufReadable, McBufWritable};
use azalea_chat::component::Component;
use azalea_core::{BlockPos, Direction, Particle, Slot};
@@ -17,7 +17,7 @@ pub struct EntityDataItem {
}
impl McBufReadable for EntityMetadata {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
let mut metadata = Vec::new();
loop {
let index = u8::read_from(buf)?;
@@ -70,8 +70,8 @@ pub enum EntityDataValue {
}
impl McBufReadable for EntityDataValue {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
- let data_type = i32::var_read_from(buf)?;
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
+ let data_type = u32::var_read_from(buf)?;
Ok(match data_type {
0 => EntityDataValue::Byte(u8::read_from(buf)?),
1 => EntityDataValue::Int(i32::var_read_from(buf)?),
@@ -110,7 +110,11 @@ impl McBufReadable for EntityDataValue {
}
}),
18 => EntityDataValue::Pose(Pose::read_from(buf)?),
- _ => return Err(format!("Unknown entity data type: {}", data_type)),
+ _ => {
+ return Err(BufReadError::UnexpectedEnumVariant {
+ id: data_type as i32,
+ })
+ }
})
}
}
diff --git a/azalea-nbt/src/decode.rs b/azalea-nbt/src/decode.rs
index 5f0e8fd2..12c13448 100755
--- a/azalea-nbt/src/decode.rs
+++ b/azalea-nbt/src/decode.rs
@@ -1,5 +1,6 @@
use crate::Error;
use crate::Tag;
+use azalea_buf::BufReadError;
use azalea_buf::McBufReadable;
use byteorder::{ReadBytesExt, BE};
use flate2::read::{GzDecoder, ZlibDecoder};
@@ -139,7 +140,7 @@ impl Tag {
}
impl McBufReadable for Tag {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
match Tag::read(buf) {
Ok(r) => Ok(r),
// Err(e) => Err(e.to_string()),
diff --git a/azalea-protocol/Cargo.toml b/azalea-protocol/Cargo.toml
index 17884a51..bd475676 100755
--- a/azalea-protocol/Cargo.toml
+++ b/azalea-protocol/Cargo.toml
@@ -22,7 +22,7 @@ flate2 = "1.0.23"
packet-macros = {path = "./packet-macros"}
serde = {version = "1.0.130", features = ["serde_derive"]}
serde_json = "^1.0.72"
-thiserror = "^1.0.30"
+thiserror = "^1.0.32"
tokio = {version = "^1.19.2", features = ["io-util", "net", "macros"]}
tokio-util = "^0.6.9"
trust-dns-resolver = "^0.20.3"
diff --git a/azalea-protocol/packet-macros/src/lib.rs b/azalea-protocol/packet-macros/src/lib.rs
index ea4db210..f96a85c7 100755..100644
--- a/azalea-protocol/packet-macros/src/lib.rs
+++ b/azalea-protocol/packet-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,
- ) -> Result<#state, String> {
+ ) -> Result<#state, azalea_buf::BufReadError> {
use azalea_buf::McBufReadable;
Ok(Self::read_from(buf)?.get())
}
@@ -206,6 +206,7 @@ pub fn declare_state_packets(input: TokenStream) -> TokenStream {
let mut clientbound_read_match_contents = quote!();
for PacketIdPair { id, module, name } in input.serverbound.packets {
+ let name_litstr = syn::LitStr::new(&name.to_string(), name.span());
serverbound_enum_contents.extend(quote! {
#name(#module::#name),
});
@@ -216,11 +217,19 @@ pub fn declare_state_packets(input: TokenStream) -> TokenStream {
#serverbound_state_name::#name(packet) => packet.write(buf),
});
serverbound_read_match_contents.extend(quote! {
- #id => #module::#name::read(buf)?,
+ #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);
+ if !leftover.is_empty() {
+ return Err(crate::read::ReadPacketError::LeftoverData { packet_name: #name_litstr.to_string(), data: leftover });
+ }
+ data
+ },
});
}
for PacketIdPair { id, module, name } in input.clientbound.packets {
- // let name_litstr = syn::LitStr::new(&name.to_string(), name.span());
+ let name_litstr = syn::LitStr::new(&name.to_string(), name.span());
clientbound_enum_contents.extend(quote! {
#name(#module::#name),
});
@@ -231,7 +240,15 @@ pub fn declare_state_packets(input: TokenStream) -> TokenStream {
#clientbound_state_name::#name(packet) => packet.write(buf),
});
clientbound_read_match_contents.extend(quote! {
- #id => #module::#name::read(buf)?,
+ #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);
+ if !leftover.is_empty() {
+ return Err(crate::read::ReadPacketError::LeftoverData { packet_name: #name_litstr.to_string(), data: leftover });
+ }
+ data
+ },
});
}
@@ -288,13 +305,13 @@ pub fn declare_state_packets(input: TokenStream) -> TokenStream {
fn read(
id: u32,
buf: &mut impl std::io::Read,
- ) -> Result<#serverbound_state_name, String>
+ ) -> Result<#serverbound_state_name, crate::read::ReadPacketError>
where
Self: Sized,
{
Ok(match id {
#serverbound_read_match_contents
- _ => return Err(format!("Unknown Serverbound {} packet id: {}", #state_name_litstr, id)),
+ _ => return Err(crate::read::ReadPacketError::UnknownPacketId { state_name: #state_name_litstr.to_string(), id }),
})
}
}
@@ -319,13 +336,13 @@ pub fn declare_state_packets(input: TokenStream) -> TokenStream {
fn read(
id: u32,
buf: &mut impl std::io::Read,
- ) -> Result<#clientbound_state_name, String>
+ ) -> Result<#clientbound_state_name, crate::read::ReadPacketError>
where
Self: Sized,
{
Ok(match id {
#clientbound_read_match_contents
- _ => return Err(format!("Unknown Clientbound {} packet id: {}", #state_name_litstr, id)),
+ _ => return Err(crate::read::ReadPacketError::UnknownPacketId { state_name: #state_name_litstr.to_string(), id }),
})
}
}
diff --git a/azalea-protocol/src/connect.rs b/azalea-protocol/src/connect.rs
index cd51f86c..e29ba1df 100755
--- a/azalea-protocol/src/connect.rs
+++ b/azalea-protocol/src/connect.rs
@@ -5,12 +5,13 @@ use crate::packets::handshake::{ClientboundHandshakePacket, ServerboundHandshake
use crate::packets::login::{ClientboundLoginPacket, ServerboundLoginPacket};
use crate::packets::status::{ClientboundStatusPacket, ServerboundStatusPacket};
use crate::packets::ProtocolPacket;
-use crate::read::read_packet;
+use crate::read::{read_packet, ReadPacketError};
use crate::write::write_packet;
use crate::ServerIpAddress;
use azalea_crypto::{Aes128CfbDec, Aes128CfbEnc};
use std::fmt::Debug;
use std::marker::PhantomData;
+use thiserror::Error;
use tokio::net::TcpStream;
pub struct Connection<R: ProtocolPacket, W: ProtocolPacket> {
@@ -28,7 +29,7 @@ where
R: ProtocolPacket + Debug,
W: ProtocolPacket + Debug,
{
- pub async fn read(&mut self) -> Result<R, String> {
+ pub async fn read(&mut self) -> Result<R, ReadPacketError> {
read_packet::<R, _>(
&mut self.stream,
self.compression_threshold,
@@ -38,30 +39,32 @@ where
}
/// Write a packet to the server
- pub async fn write(&mut self, packet: W) {
+ pub async fn write(&mut self, packet: W) -> std::io::Result<()> {
write_packet(
packet,
&mut self.stream,
self.compression_threshold,
&mut self.enc_cipher,
)
- .await;
+ .await
}
}
+#[derive(Error, Debug)]
+pub enum ConnectionError {
+ #[error("{0}")]
+ Io(#[from] std::io::Error),
+}
+
impl Connection<ClientboundHandshakePacket, ServerboundHandshakePacket> {
- pub async fn new(address: &ServerIpAddress) -> Result<Self, String> {
+ pub async fn new(address: &ServerIpAddress) -> Result<Self, ConnectionError> {
let ip = address.ip;
let port = address.port;
- let stream = TcpStream::connect(format!("{}:{}", ip, port))
- .await
- .map_err(|_| "Failed to connect to server")?;
+ let stream = TcpStream::connect(format!("{}:{}", ip, port)).await?;
// enable tcp_nodelay
- stream
- .set_nodelay(true)
- .expect("Error enabling tcp_nodelay");
+ stream.set_nodelay(true)?;
Ok(Connection {
stream,
diff --git a/azalea-protocol/src/packets/game/clientbound_declare_commands_packet.rs b/azalea-protocol/src/packets/game/clientbound_declare_commands_packet.rs
index f45946d5..622b9ec7 100755
--- a/azalea-protocol/src/packets/game/clientbound_declare_commands_packet.rs
+++ b/azalea-protocol/src/packets/game/clientbound_declare_commands_packet.rs
@@ -1,3 +1,4 @@
+use azalea_buf::BufReadError;
use azalea_buf::McBuf;
use azalea_buf::McBufVarReadable;
use azalea_buf::{McBufReadable, McBufWritable, Readable, Writable};
@@ -24,7 +25,7 @@ pub struct BrigadierNumber<T> {
max: Option<T>,
}
impl<T: McBufReadable> McBufReadable for BrigadierNumber<T> {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
let flags = buf.read_byte()?;
let min = if flags & 0x01 != 0 {
Some(T::read_from(buf)?)
@@ -123,7 +124,7 @@ pub enum BrigadierParser {
}
impl McBufReadable for BrigadierParser {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
let parser_type = u32::var_read_from(buf)?;
match parser_type {
@@ -190,14 +191,16 @@ impl McBufReadable for BrigadierParser {
45 => Ok(BrigadierParser::TemplateMirror),
46 => Ok(BrigadierParser::TemplateRotation),
47 => Ok(BrigadierParser::Uuid),
- _ => Err(format!("Unknown BrigadierParser type: {}", parser_type)),
+ _ => Err(BufReadError::UnexpectedEnumVariant {
+ id: parser_type as i32,
+ }),
}
}
}
// TODO: BrigadierNodeStub should have more stuff
impl McBufReadable for BrigadierNodeStub {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
let flags = u8::read_from(buf)?;
if flags > 31 {
println!(
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 8b52b8cf..d85f39cb 100644
--- a/azalea-protocol/src/packets/game/clientbound_level_particles_packet.rs
+++ b/azalea-protocol/src/packets/game/clientbound_level_particles_packet.rs
@@ -1,4 +1,4 @@
-use azalea_buf::{McBufReadable, McBufVarReadable, McBufWritable};
+use azalea_buf::{BufReadError, McBufReadable, McBufVarReadable, McBufWritable};
use azalea_core::ParticleData;
use packet_macros::ClientboundGamePacket;
use std::io::{Read, Write};
@@ -20,7 +20,7 @@ pub struct ClientboundLevelParticlesPacket {
}
impl McBufReadable for ClientboundLevelParticlesPacket {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> 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_player_abilities_packet.rs b/azalea-protocol/src/packets/game/clientbound_player_abilities_packet.rs
index 9a312276..5ab187ae 100755
--- a/azalea-protocol/src/packets/game/clientbound_player_abilities_packet.rs
+++ b/azalea-protocol/src/packets/game/clientbound_player_abilities_packet.rs
@@ -1,4 +1,4 @@
-use azalea_buf::McBuf;
+use azalea_buf::{BufReadError, McBuf};
use azalea_buf::{McBufReadable, McBufWritable, Readable};
use packet_macros::ClientboundGamePacket;
use std::io::{Read, Write};
@@ -20,7 +20,7 @@ pub struct PlayerAbilitiesFlags {
}
impl McBufReadable for PlayerAbilitiesFlags {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
let byte = buf.read_byte()?;
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 a2caae4b..7414e10c 100644
--- a/azalea-protocol/src/packets/game/clientbound_player_chat_packet.rs
+++ b/azalea-protocol/src/packets/game/clientbound_player_chat_packet.rs
@@ -1,4 +1,4 @@
-use azalea_buf::{BitSet, McBuf, McBufReadable, McBufVarWritable};
+use azalea_buf::{BitSet, BufReadError, McBuf, McBufReadable, McBufVarWritable};
use azalea_buf::{McBufVarReadable, McBufWritable};
use azalea_chat::component::Component;
use azalea_crypto::{MessageSignature, SignedMessageHeader};
@@ -74,13 +74,15 @@ pub enum FilterMask {
}
impl McBufReadable for FilterMask {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
let filter_mask = u32::var_read_from(buf)?;
match filter_mask {
0 => Ok(FilterMask::PassThrough),
1 => Ok(FilterMask::FullyFiltered),
2 => Ok(FilterMask::PartiallyFiltered(BitSet::read_from(buf)?)),
- _ => Err("Invalid filter mask".to_string()),
+ _ => Err(BufReadError::UnexpectedEnumVariant {
+ id: filter_mask as i32,
+ }),
}
}
}
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 614a351e..d53774b7 100644
--- a/azalea-protocol/src/packets/game/clientbound_player_info_packet.rs
+++ b/azalea-protocol/src/packets/game/clientbound_player_info_packet.rs
@@ -1,4 +1,4 @@
-use azalea_buf::McBuf;
+use azalea_buf::{BufReadError, McBuf};
use azalea_buf::{McBufReadable, McBufWritable, Readable, Writable};
use azalea_chat::component::Component;
use packet_macros::ClientboundGamePacket;
@@ -63,7 +63,7 @@ pub struct RemovePlayer {
}
impl McBufReadable for Action {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
let id = buf.read_byte()?;
Ok(match id {
0 => Action::AddPlayer(Vec::<AddPlayer>::read_from(buf)?),
@@ -71,7 +71,7 @@ impl McBufReadable for Action {
2 => Action::UpdateLatency(Vec::<UpdateLatency>::read_from(buf)?),
3 => Action::UpdateDisplayName(Vec::<UpdateDisplayName>::read_from(buf)?),
4 => Action::RemovePlayer(Vec::<RemovePlayer>::read_from(buf)?),
- _ => panic!("Unknown player info action id: {}", id),
+ _ => return Err(BufReadError::UnexpectedEnumVariant { id: id.into() }),
})
}
}
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 758e6bb0..d4c9dcb5 100644
--- a/azalea-protocol/src/packets/game/clientbound_player_position_packet.rs
+++ b/azalea-protocol/src/packets/game/clientbound_player_position_packet.rs
@@ -1,4 +1,4 @@
-use azalea_buf::McBuf;
+use azalea_buf::{BufReadError, McBuf};
use azalea_buf::{McBufReadable, McBufWritable, Readable};
use packet_macros::ClientboundGamePacket;
use std::io::{Read, Write};
@@ -28,7 +28,7 @@ pub struct RelativeArguments {
}
impl McBufReadable for RelativeArguments {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
let byte = buf.read_byte()?;
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 e6a5bf7f..05e96f69 100644
--- a/azalea-protocol/src/packets/game/clientbound_recipe_packet.rs
+++ b/azalea-protocol/src/packets/game/clientbound_recipe_packet.rs
@@ -1,4 +1,4 @@
-use azalea_buf::McBuf;
+use azalea_buf::{BufReadError, McBuf};
use azalea_buf::{McBufReadable, McBufWritable, Readable, Writable};
use azalea_core::ResourceLocation;
use packet_macros::ClientboundGamePacket;
@@ -41,7 +41,7 @@ impl McBufWritable for State {
}
}
impl McBufReadable for State {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
let state = buf.read_varint()?;
Ok(match state {
0 => State::Init,
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 0a83edf0..5dee398e 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
@@ -1,4 +1,4 @@
-use azalea_buf::McBuf;
+use azalea_buf::{BufReadError, McBuf};
use azalea_buf::{McBufReadable, McBufVarReadable, McBufVarWritable, McBufWritable};
use azalea_core::{ChunkSectionBlockPos, ChunkSectionPos};
use packet_macros::ClientboundGamePacket;
@@ -18,7 +18,7 @@ pub struct BlockStateWithPosition {
}
impl McBufReadable for BlockStateWithPosition {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> 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 102e90e1..35f0d251 100644
--- a/azalea-protocol/src/packets/game/clientbound_set_equipment_packet.rs
+++ b/azalea-protocol/src/packets/game/clientbound_set_equipment_packet.rs
@@ -1,4 +1,4 @@
-use azalea_buf::McBuf;
+use azalea_buf::{BufReadError, McBuf};
use azalea_core::Slot;
use packet_macros::ClientboundGamePacket;
@@ -17,13 +17,17 @@ pub struct EquipmentSlots {
}
impl McBufReadable for EquipmentSlots {
- fn read_from(buf: &mut impl std::io::Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl std::io::Read) -> Result<Self, BufReadError> {
let mut slots = vec![];
loop {
let equipment_byte = u8::read_from(buf)?;
- let equipment_slot = EquipmentSlot::from_byte(equipment_byte & 127)
- .ok_or_else(|| format!("Invalid equipment slot byte {}", equipment_byte))?;
+ let equipment_slot =
+ EquipmentSlot::from_byte(equipment_byte & 127).ok_or_else(|| {
+ BufReadError::UnexpectedEnumVariant {
+ id: equipment_byte.into(),
+ }
+ })?;
let item = Slot::read_from(buf)?;
slots.push((equipment_slot, item));
if equipment_byte & 128 == 0 {
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 396c0fa4..88cb15e9 100644
--- a/azalea-protocol/src/packets/game/clientbound_update_advancements_packet.rs
+++ b/azalea-protocol/src/packets/game/clientbound_update_advancements_packet.rs
@@ -1,4 +1,4 @@
-use azalea_buf::{McBuf, McBufReadable, McBufWritable};
+use azalea_buf::{BufReadError, McBuf, McBufReadable, McBufWritable};
use azalea_chat::component::Component;
use azalea_core::{ResourceLocation, Slot};
use packet_macros::ClientboundGamePacket;
@@ -45,7 +45,7 @@ pub struct DisplayFlags {
}
impl McBufReadable for DisplayFlags {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
let data = u32::read_from(buf)?;
Ok(DisplayFlags {
background: (data & 0b1) != 0,
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 b8785a66..6bb41a81 100644
--- a/azalea-protocol/src/packets/game/clientbound_update_attributes_packet.rs
+++ b/azalea-protocol/src/packets/game/clientbound_update_attributes_packet.rs
@@ -1,4 +1,4 @@
-use azalea_buf::McBuf;
+use azalea_buf::{BufReadError, McBuf};
use azalea_buf::{McBufReadable, McBufWritable, Readable, Writable};
use azalea_core::ResourceLocation;
use packet_macros::ClientboundGamePacket;
@@ -34,12 +34,12 @@ enum Operation {
}
impl McBufReadable for Operation {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
match buf.read_byte()? {
0 => Ok(Operation::Addition),
1 => Ok(Operation::MultiplyBase),
2 => Ok(Operation::MultiplyTotal),
- op => Err(format!("Unknown operation: {}", op)),
+ id => Err(BufReadError::UnexpectedEnumVariant { id: id.into() }),
}
}
}
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 7a96629b..da1485d0 100644
--- a/azalea-protocol/src/packets/game/clientbound_update_recipes_packet.rs
+++ b/azalea-protocol/src/packets/game/clientbound_update_recipes_packet.rs
@@ -1,6 +1,6 @@
use std::io::{Read, Write};
-use azalea_buf::McBuf;
+use azalea_buf::{BufReadError, McBuf};
use azalea_core::{ResourceLocation, Slot};
use packet_macros::ClientboundGamePacket;
@@ -49,7 +49,7 @@ impl McBufWritable for ShapedRecipe {
}
}
impl McBufReadable for ShapedRecipe {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
let width = buf.read_varint()?.try_into().unwrap();
let height = buf.read_varint()?.try_into().unwrap();
let group = buf.read_utf()?;
@@ -129,7 +129,7 @@ impl McBufWritable for Recipe {
}
impl McBufReadable for Recipe {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> 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 6d567cfa..6f0fe778 100755
--- a/azalea-protocol/src/packets/game/clientbound_update_tags_packet.rs
+++ b/azalea-protocol/src/packets/game/clientbound_update_tags_packet.rs
@@ -1,4 +1,4 @@
-use azalea_buf::McBuf;
+use azalea_buf::{BufReadError, McBuf};
use azalea_buf::{McBufReadable, McBufWritable, Readable, Writable};
use azalea_core::ResourceLocation;
use packet_macros::ClientboundGamePacket;
@@ -23,7 +23,7 @@ pub struct Tags {
pub struct TagMap(HashMap<ResourceLocation, Vec<Tags>>);
impl McBufReadable for TagMap {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
let length = buf.read_varint()? as usize;
let mut data = HashMap::with_capacity(length);
for _ in 0..length {
@@ -51,7 +51,7 @@ impl McBufWritable for TagMap {
}
}
impl McBufReadable for Tags {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
let name = ResourceLocation::read_from(buf)?;
let elements = buf.read_int_id_list()?;
Ok(Tags { name, elements })
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 9d9ce35b..93421cc2 100755
--- a/azalea-protocol/src/packets/login/clientbound_game_profile_packet.rs
+++ b/azalea-protocol/src/packets/login/clientbound_game_profile_packet.rs
@@ -2,34 +2,11 @@ use std::io::{Read, Write};
use super::ClientboundLoginPacket;
use azalea_auth::game_profile::GameProfile;
-use azalea_buf::{McBufReadable, Readable, SerializableUuid, Writable};
+use azalea_buf::{BufReadError, McBuf, McBufReadable, Readable, SerializableUuid, Writable};
+use packet_macros::ClientboundLoginPacket;
use uuid::Uuid;
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, McBuf, ClientboundLoginPacket)]
pub struct ClientboundGameProfilePacket {
pub game_profile: GameProfile,
}
-
-// TODO: add derives to GameProfile and have an impl McBufReadable/Writable for GameProfile
-impl ClientboundGameProfilePacket {
- pub fn get(self) -> ClientboundLoginPacket {
- ClientboundLoginPacket::ClientboundGameProfilePacket(self)
- }
-
- pub fn write(&self, buf: &mut impl Write) -> 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 fn read(buf: &mut impl Read) -> Result<ClientboundLoginPacket, String> {
- let uuid = Uuid::read_from(buf)?;
- let name = buf.read_utf_with_len(16)?;
- Ok(ClientboundGameProfilePacket {
- game_profile: GameProfile::new(uuid, name),
- }
- .get())
- }
-}
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 39314041..26321f34 100755
--- a/azalea-protocol/src/packets/login/clientbound_login_compression_packet.rs
+++ b/azalea-protocol/src/packets/login/clientbound_login_compression_packet.rs
@@ -3,7 +3,7 @@ use std::{
io::{Read, Write},
};
-use azalea_buf::{Readable, Writable};
+use azalea_buf::{BufReadError, Readable, Writable};
use super::ClientboundLoginPacket;
@@ -22,7 +22,7 @@ impl ClientboundLoginCompressionPacket {
Ok(())
}
- pub fn read(buf: &mut impl Read) -> Result<ClientboundLoginPacket, String> {
+ pub fn read(buf: &mut impl Read) -> Result<ClientboundLoginPacket, BufReadError> {
let compression_threshold = buf.read_varint()?;
Ok(ClientboundLoginCompressionPacket {
diff --git a/azalea-protocol/src/packets/login/serverbound_key_packet.rs b/azalea-protocol/src/packets/login/serverbound_key_packet.rs
index 62dc6252..54f268e7 100644
--- a/azalea-protocol/src/packets/login/serverbound_key_packet.rs
+++ b/azalea-protocol/src/packets/login/serverbound_key_packet.rs
@@ -1,4 +1,4 @@
-use azalea_buf::McBuf;
+use azalea_buf::{BufReadError, McBuf};
use azalea_crypto::SaltSignaturePair;
use packet_macros::ServerboundLoginPacket;
use std::io::{Read, Write};
@@ -18,7 +18,7 @@ pub enum NonceOrSaltSignature {
}
impl McBufReadable for NonceOrSaltSignature {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> 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 228d7c74..da1631a0 100644
--- a/azalea-protocol/src/packets/mod.rs
+++ b/azalea-protocol/src/packets/mod.rs
@@ -3,7 +3,8 @@ pub mod handshake;
pub mod login;
pub mod status;
-use azalea_buf::{McBufWritable, Readable, Writable};
+use crate::read::ReadPacketError;
+use azalea_buf::{BufReadError, McBufWritable, Readable, Writable};
use std::io::{Read, Write};
pub const PROTOCOL_VERSION: u32 = 760;
@@ -36,15 +37,15 @@ where
fn id(&self) -> u32;
/// Read a packet by its id, ConnectionProtocol, and flow
- fn read(id: u32, buf: &mut impl Read) -> Result<Self, String>;
+ fn read(id: u32, buf: &mut impl Read) -> 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, String> {
- ConnectionProtocol::from_i32(buf.read_varint()?)
- .ok_or_else(|| "Invalid intention".to_string())
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
+ let id = buf.read_varint()?;
+ 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 2e4116fa..8724816b 100755
--- a/azalea-protocol/src/packets/status/clientbound_status_response_packet.rs
+++ b/azalea-protocol/src/packets/status/clientbound_status_response_packet.rs
@@ -1,5 +1,5 @@
use super::ClientboundStatusPacket;
-use azalea_buf::Readable;
+use azalea_buf::{BufReadError, Readable};
use azalea_chat::component::Component;
use serde::Deserialize;
use serde_json::Value;
@@ -42,14 +42,11 @@ impl ClientboundStatusResponsePacket {
Ok(())
}
- pub fn read(buf: &mut impl Read) -> Result<ClientboundStatusPacket, String> {
+ pub fn read(buf: &mut impl Read) -> Result<ClientboundStatusPacket, BufReadError> {
let status_string = buf.read_utf()?;
- let status_json: Value =
- serde_json::from_str(status_string.as_str()).expect("Server status isn't valid JSON");
+ let status_json: Value = serde_json::from_str(status_string.as_str())?;
- let packet = ClientboundStatusResponsePacket::deserialize(status_json)
- .map_err(|e| e.to_string())?
- .get();
+ let packet = ClientboundStatusResponsePacket::deserialize(status_json)?.get();
Ok(packet)
}
diff --git a/azalea-protocol/src/read.rs b/azalea-protocol/src/read.rs
index 6a56ccfb..077e1297 100755
--- a/azalea-protocol/src/read.rs
+++ b/azalea-protocol/src/read.rs
@@ -1,5 +1,6 @@
use crate::packets::ProtocolPacket;
-use azalea_buf::{read_varint_async, Readable};
+use azalea_buf::McBufVarReadable;
+use azalea_buf::{read_varint_async, BufReadError, Readable};
use azalea_crypto::Aes128CfbDec;
use flate2::read::ZlibDecoder;
use std::{
@@ -8,32 +9,67 @@ use std::{
pin::Pin,
task::{Context, Poll},
};
+use thiserror::Error;
use tokio::io::{AsyncRead, AsyncReadExt};
-async fn frame_splitter<R: ?Sized>(mut stream: &mut R) -> Result<Vec<u8>, String>
+#[derive(Error, Debug)]
+pub enum ReadPacketError {
+ #[error("Error reading packet {packet_name} ({packet_id}): {source}")]
+ Parse {
+ packet_id: u32,
+ packet_name: String,
+ source: BufReadError,
+ },
+ #[error("Unknown packet id {id} in state {state_name}")]
+ UnknownPacketId { state_name: String, id: u32 },
+ #[error("Couldn't read packet id")]
+ ReadPacketId { source: BufReadError },
+ #[error("Couldn't decompress packet")]
+ Decompress {
+ #[from]
+ source: DecompressionError,
+ },
+ #[error("Frame splitter error")]
+ FrameSplitter {
+ #[from]
+ source: FrameSplitterError,
+ },
+ #[error("Leftover data after reading packet {packet_name}: {data:?}")]
+ LeftoverData { data: Vec<u8>, packet_name: String },
+}
+
+#[derive(Error, Debug)]
+pub enum FrameSplitterError {
+ #[error("Couldn't read VarInt length for packet. The previous packet may have been corrupted")]
+ LengthRead {
+ #[from]
+ source: BufReadError,
+ },
+ #[error("Io error")]
+ Io {
+ #[from]
+ source: std::io::Error,
+ },
+}
+
+async fn frame_splitter<R: ?Sized>(mut stream: &mut R) -> Result<Vec<u8>, FrameSplitterError>
where
R: AsyncRead + std::marker::Unpin + std::marker::Send,
{
// Packet Length
- let length_result = read_varint_async(&mut stream).await;
- match length_result {
- Ok(length) => {
- let mut buf = vec![0; length as usize];
+ let length = read_varint_async(&mut stream).await?;
- stream
- .read_exact(&mut buf)
- .await
- .map_err(|e| e.to_string())?;
+ let mut buf = vec![0; length as usize];
+ stream.read_exact(&mut buf).await?;
- Ok(buf)
- }
- Err(_) => Err("length wider than 21-bit".to_string()),
- }
+ Ok(buf)
}
-fn packet_decoder<P: ProtocolPacket>(stream: &mut impl Read) -> Result<P, String> {
+fn packet_decoder<P: ProtocolPacket>(stream: &mut impl Read) -> Result<P, ReadPacketError> {
// Packet ID
- let packet_id = stream.read_varint()?;
+ let packet_id = stream
+ .read_varint()
+ .map_err(|e| ReadPacketError::ReadPacketId { source: e })?;
P::read(packet_id.try_into().unwrap(), stream)
}
@@ -42,39 +78,57 @@ static VALIDATE_DECOMPRESSED: bool = true;
pub static MAXIMUM_UNCOMPRESSED_LENGTH: u32 = 2097152;
+#[derive(Error, Debug)]
+pub enum DecompressionError {
+ #[error("Couldn't read VarInt length for data")]
+ LengthReadError {
+ #[from]
+ source: BufReadError,
+ },
+ #[error("Io error")]
+ Io {
+ #[from]
+ source: std::io::Error,
+ },
+ #[error("Badly compressed packet - size of {size} is below server threshold of {threshold}")]
+ BelowCompressionThreshold { size: u32, threshold: u32 },
+ #[error(
+ "Badly compressed packet - size of {size} is larger than protocol maximum of {maximum}"
+ )]
+ AboveCompressionThreshold { size: u32, maximum: u32 },
+}
+
fn compression_decoder(
stream: &mut impl Read,
compression_threshold: u32,
-) -> Result<Vec<u8>, String> {
+) -> Result<Vec<u8>, DecompressionError> {
// Data Length
- let n: u32 = stream.read_varint()?.try_into().unwrap();
+ let n = u32::var_read_from(stream)?;
if n == 0 {
// no data size, no compression
let mut buf = vec![];
- stream.read_to_end(&mut buf).map_err(|e| e.to_string())?;
+ stream.read_to_end(&mut buf)?;
return Ok(buf);
}
if VALIDATE_DECOMPRESSED {
if n < compression_threshold {
- return Err(format!(
- "Badly compressed packet - size of {} is below server threshold of {}",
- n, compression_threshold
- ));
+ return Err(DecompressionError::BelowCompressionThreshold {
+ size: n,
+ threshold: compression_threshold,
+ });
}
if n > MAXIMUM_UNCOMPRESSED_LENGTH {
- return Err(format!(
- "Badly compressed packet - size of {} is larger than protocol maximum of {}",
- n, MAXIMUM_UNCOMPRESSED_LENGTH
- ));
+ return Err(DecompressionError::AboveCompressionThreshold {
+ size: n,
+ maximum: MAXIMUM_UNCOMPRESSED_LENGTH,
+ });
}
}
let mut decoded_buf = vec![];
let mut decoder = ZlibDecoder::new(stream);
- decoder
- .read_to_end(&mut decoded_buf)
- .map_err(|e| e.to_string())?;
+ decoder.read_to_end(&mut decoded_buf)?;
Ok(decoded_buf)
}
@@ -121,7 +175,7 @@ pub async fn read_packet<'a, P: ProtocolPacket, R>(
stream: &'a mut R,
compression_threshold: Option<u32>,
cipher: &mut Option<Aes128CfbDec>,
-) -> Result<P, String>
+) -> Result<P, ReadPacketError>
where
R: AsyncRead + std::marker::Unpin + std::marker::Send + std::marker::Sync,
{
@@ -149,5 +203,7 @@ where
let packet = packet_decoder(&mut buf.as_slice())?;
// println!("decoded packet ({}ms)", start_time.elapsed().as_millis());
+ if !buf.is_empty() {}
+
Ok(packet)
}
diff --git a/azalea-protocol/src/resolver.rs b/azalea-protocol/src/resolver.rs
index 24687a6e..e21362a5 100755
--- a/azalea-protocol/src/resolver.rs
+++ b/azalea-protocol/src/resolver.rs
@@ -1,16 +1,24 @@
-use std::net::IpAddr;
-
use crate::{ServerAddress, ServerIpAddress};
use async_recursion::async_recursion;
+use std::net::IpAddr;
+use thiserror::Error;
use trust_dns_resolver::{
config::{ResolverConfig, ResolverOpts},
TokioAsyncResolver,
};
+#[derive(Error, Debug)]
+pub enum ResolverError {
+ #[error("No SRV record found")]
+ NoSrvRecord,
+ #[error("No IP found")]
+ NoIp,
+}
+
/// Resolve a Minecraft server address into an IP address and port.
/// If it's already an IP address, it's returned as-is.
#[async_recursion]
-pub async fn resolve_address(address: &ServerAddress) -> Result<ServerIpAddress, String> {
+pub async fn resolve_address(address: &ServerAddress) -> Result<ServerIpAddress, ResolverError> {
// If the address.host is already in the format of an ip address, return it.
if let Ok(ip) = address.host.parse::<IpAddr>() {
return Ok(ServerIpAddress {
@@ -33,20 +41,20 @@ pub async fn resolve_address(address: &ServerAddress) -> Result<ServerIpAddress,
let redirect_srv = redirect_result
.iter()
.next()
- .ok_or_else(|| "No SRV record found".to_string())?;
+ .ok_or(ResolverError::NoSrvRecord)?;
let redirect_address = ServerAddress {
host: redirect_srv.target().to_utf8(),
port: redirect_srv.port(),
};
- println!("redirecting to {:?}", redirect_address);
+ // println!("redirecting to {:?}", redirect_address);
return resolve_address(&redirect_address).await;
}
// there's no redirect, try to resolve this as an ip address
let lookup_ip_result = resolver.lookup_ip(address.host.clone()).await;
- let lookup_ip = lookup_ip_result.map_err(|_| "No IP found".to_string())?;
+ let lookup_ip = lookup_ip_result.map_err(|_| ResolverError::NoIp)?;
Ok(ServerIpAddress {
ip: lookup_ip.iter().next().unwrap(),
diff --git a/azalea-protocol/src/write.rs b/azalea-protocol/src/write.rs
index ae9a6829..30710f8b 100755
--- a/azalea-protocol/src/write.rs
+++ b/azalea-protocol/src/write.rs
@@ -3,49 +3,67 @@ use async_compression::tokio::bufread::ZlibEncoder;
use azalea_buf::Writable;
use azalea_crypto::Aes128CfbEnc;
use std::fmt::Debug;
+use thiserror::Error;
use tokio::io::{AsyncReadExt, AsyncWrite, AsyncWriteExt};
-fn frame_prepender(data: &mut Vec<u8>) -> Result<Vec<u8>, String> {
+fn frame_prepender(data: &mut Vec<u8>) -> Result<Vec<u8>, std::io::Error> {
let mut buf = Vec::new();
- buf.write_varint(data.len() as i32)
- .map_err(|e| e.to_string())?;
+ buf.write_varint(data.len() as i32)?;
buf.append(data);
Ok(buf)
}
-fn packet_encoder<P: ProtocolPacket + std::fmt::Debug>(packet: &P) -> Result<Vec<u8>, String> {
+#[derive(Error, Debug)]
+pub enum PacketEncodeError {
+ #[error("{0}")]
+ Io(#[from] std::io::Error),
+ #[error("Packet too big (is {actual} bytes, should be less than {maximum}): {packet_string}")]
+ TooBig {
+ actual: usize,
+ maximum: usize,
+ packet_string: String,
+ },
+}
+
+fn packet_encoder<P: ProtocolPacket + std::fmt::Debug>(
+ packet: &P,
+) -> Result<Vec<u8>, PacketEncodeError> {
let mut buf = Vec::new();
- buf.write_varint(packet.id() as i32)
- .map_err(|e| e.to_string())?;
- packet.write(&mut buf).map_err(|e| e.to_string())?;
+ buf.write_varint(packet.id() as i32)?;
+ packet.write(&mut buf)?;
if buf.len() > MAXIMUM_UNCOMPRESSED_LENGTH as usize {
- return Err(format!(
- "Packet too big (is {} bytes, should be less than {}): {:?}",
- buf.len(),
- MAXIMUM_UNCOMPRESSED_LENGTH,
- packet
- ));
+ return Err(PacketEncodeError::TooBig {
+ actual: buf.len(),
+ maximum: MAXIMUM_UNCOMPRESSED_LENGTH as usize,
+ packet_string: format!("{:?}", packet),
+ });
}
Ok(buf)
}
-async fn compression_encoder(data: &[u8], compression_threshold: u32) -> Result<Vec<u8>, String> {
+#[derive(Error, Debug)]
+pub enum PacketCompressError {
+ #[error("{0}")]
+ Io(#[from] std::io::Error),
+}
+
+async fn compression_encoder(
+ data: &[u8],
+ compression_threshold: u32,
+) -> Result<Vec<u8>, PacketCompressError> {
let n = data.len();
// if it's less than the compression threshold, don't compress
if n < compression_threshold as usize {
let mut buf = Vec::new();
- buf.write_varint(0).map_err(|e| e.to_string())?;
- buf.write_all(data).await.map_err(|e| e.to_string())?;
+ buf.write_varint(0)?;
+ buf.write_all(data).await?;
Ok(buf)
} else {
// otherwise, compress
let mut deflater = ZlibEncoder::new(data);
// write deflated data to buf
let mut buf = Vec::new();
- deflater
- .read_to_end(&mut buf)
- .await
- .map_err(|e| e.to_string())?;
+ deflater.read_to_end(&mut buf).await?;
Ok(buf)
}
}
@@ -55,7 +73,8 @@ pub async fn write_packet<P, W>(
stream: &mut W,
compression_threshold: Option<u32>,
cipher: &mut Option<Aes128CfbEnc>,
-) where
+) -> std::io::Result<()>
+where
P: ProtocolPacket + Debug,
W: AsyncWrite + Unpin + Send,
{
@@ -68,5 +87,5 @@ pub async fn write_packet<P, W>(
if let Some(cipher) = cipher {
azalea_crypto::encrypt_packet(cipher, &mut buf);
}
- stream.write_all(&buf).await.unwrap();
+ stream.write_all(&buf).await
}
diff --git a/azalea-world/Cargo.toml b/azalea-world/Cargo.toml
index ca890d82..dca0d362 100644
--- a/azalea-world/Cargo.toml
+++ b/azalea-world/Cargo.toml
@@ -13,6 +13,7 @@ azalea-entity = {path = "../azalea-entity"}
azalea-nbt = {path = "../azalea-nbt"}
log = "0.4.17"
nohash-hasher = "0.2.0"
+thiserror = "1.0.32"
uuid = "1.1.2"
[profile.release]
diff --git a/azalea-world/src/chunk.rs b/azalea-world/src/chunk.rs
index e4893ace..9d393c2d 100644
--- a/azalea-world/src/chunk.rs
+++ b/azalea-world/src/chunk.rs
@@ -2,6 +2,7 @@ use crate::palette::PalettedContainer;
use crate::palette::PalettedContainerType;
use crate::Dimension;
use azalea_block::BlockState;
+use azalea_buf::BufReadError;
use azalea_buf::{McBufReadable, McBufWritable};
use azalea_core::{BlockPos, ChunkBlockPos, ChunkPos, ChunkSectionBlockPos};
use std::fmt::Debug;
@@ -69,7 +70,7 @@ impl ChunkStorage {
&mut self,
pos: &ChunkPos,
data: &mut impl Read,
- ) -> Result<(), String> {
+ ) -> Result<(), BufReadError> {
if !self.in_range(pos) {
println!(
"Ignoring chunk since it's not in the view range: {}, {}",
@@ -109,14 +110,17 @@ pub struct Chunk {
}
impl Chunk {
- pub fn read_with_dimension(buf: &mut impl Read, data: &Dimension) -> Result<Self, String> {
+ pub fn read_with_dimension(
+ buf: &mut impl Read,
+ data: &Dimension,
+ ) -> Result<Self, BufReadError> {
Self::read_with_dimension_height(buf, data.height())
}
pub fn read_with_dimension_height(
buf: &mut impl Read,
dimension_height: u32,
- ) -> Result<Self, String> {
+ ) -> Result<Self, BufReadError> {
let section_count = dimension_height / SECTION_HEIGHT;
let mut sections = Vec::with_capacity(section_count as usize);
for _ in 0..section_count {
@@ -174,7 +178,7 @@ pub struct Section {
}
impl McBufReadable for Section {
- fn read_from(buf: &mut impl Read) -> Result<Self, String> {
+ fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
let block_count = u16::read_from(buf)?;
// this is commented out because the vanilla server is wrong
@@ -187,11 +191,11 @@ impl McBufReadable for Section {
for i in 0..states.storage.size() {
if !BlockState::is_valid_state(states.storage.get(i) as u32) {
- return Err(format!(
+ return Err(BufReadError::Custom(format!(
"Invalid block state {} (index {}) found in section.",
states.storage.get(i),
i
- ));
+ )));
}
}
diff --git a/azalea-world/src/lib.rs b/azalea-world/src/lib.rs
index 7822dcc4..646ba1d9 100644
--- a/azalea-world/src/lib.rs
+++ b/azalea-world/src/lib.rs
@@ -6,6 +6,7 @@ mod entity;
mod palette;
use azalea_block::BlockState;
+use azalea_buf::BufReadError;
use azalea_core::{BlockPos, ChunkPos, EntityPos, PositionDelta8};
use azalea_entity::Entity;
pub use bit_storage::BitStorage;
@@ -16,6 +17,7 @@ use std::{
ops::{Index, IndexMut},
sync::{Arc, Mutex},
};
+use thiserror::Error;
use uuid::Uuid;
#[cfg(test)]
@@ -34,6 +36,12 @@ pub struct Dimension {
entity_storage: EntityStorage,
}
+#[derive(Error, Debug)]
+pub enum MoveEntityError {
+ #[error("Entity doesn't exist")]
+ EntityDoesNotExist,
+}
+
impl Dimension {
pub fn new(chunk_radius: u32, height: u32, min_y: i32) -> Self {
Dimension {
@@ -46,7 +54,7 @@ impl Dimension {
&mut self,
pos: &ChunkPos,
data: &mut impl Read,
- ) -> Result<(), String> {
+ ) -> Result<(), BufReadError> {
self.chunk_storage.replace_with_packet_data(pos, data)
}
@@ -58,11 +66,15 @@ impl Dimension {
self.chunk_storage.get_block_state(pos, self.min_y())
}
- pub fn move_entity(&mut self, entity_id: u32, new_pos: EntityPos) -> Result<(), String> {
+ pub fn move_entity(
+ &mut self,
+ entity_id: u32,
+ new_pos: EntityPos,
+ ) -> Result<(), MoveEntityError> {
let entity = self
.entity_storage
.get_mut_by_id(entity_id)
- .ok_or_else(|| "Moving entity that doesn't exist".to_string())?;
+ .ok_or(MoveEntityError::EntityDoesNotExist)?;
let old_chunk = ChunkPos::from(entity.pos());
let new_chunk = ChunkPos::from(&new_pos);
@@ -79,11 +91,11 @@ impl Dimension {
&mut self,
entity_id: u32,
delta: &PositionDelta8,
- ) -> Result<(), String> {
+ ) -> Result<(), MoveEntityError> {
let entity = self
.entity_storage
.get_mut_by_id(entity_id)
- .ok_or_else(|| "Moving entity that doesn't exist".to_string())?;
+ .ok_or(MoveEntityError::EntityDoesNotExist)?;
let new_pos = entity.pos().with_delta(delta);
let old_chunk = ChunkPos::from(entity.pos());
diff --git a/azalea-world/src/palette.rs b/azalea-world/src/palette.rs
index 1b40f257..2473a7e5 100644
--- a/azalea-world/src/palette.rs
+++ b/azalea-world/src/palette.rs
@@ -1,4 +1,6 @@
-use azalea_buf::{McBufReadable, McBufVarReadable, McBufWritable, Readable, Writable};
+use azalea_buf::{
+ BufReadError, McBufReadable, McBufVarReadable, McBufWritable, Readable, Writable,
+};
use std::io::{Read, Write};
use crate::BitStorage;
@@ -22,7 +24,7 @@ impl PalettedContainer {
pub fn read_with_type(
buf: &mut impl Read,
type_: &'static PalettedContainerType,
- ) -> Result<Self, String> {
+ ) -> Result<Self, BufReadError> {
let bits_per_entry = buf.read_byte()?;
let palette = match type_ {
PalettedContainerType::BlockStates => {
@@ -90,7 +92,7 @@ impl Palette {
pub fn block_states_read_with_bits_per_entry(
buf: &mut impl Read,
bits_per_entry: u8,
- ) -> Result<Palette, String> {
+ ) -> Result<Palette, BufReadError> {
Ok(match bits_per_entry {
0 => Palette::SingleValue(u32::var_read_from(buf)?),
1..=4 => Palette::Linear(Vec::<u32>::var_read_from(buf)?),
@@ -102,7 +104,7 @@ impl Palette {
pub fn biomes_read_with_bits_per_entry(
buf: &mut impl Read,
bits_per_entry: u8,
- ) -> Result<Palette, String> {
+ ) -> Result<Palette, BufReadError> {
Ok(match bits_per_entry {
0 => Palette::SingleValue(u32::var_read_from(buf)?),
1..=3 => Palette::Linear(Vec::<u32>::var_read_from(buf)?),