1
2
Fork 0
mirror of https://github.com/mat-1/azalea.git synced 2025-08-02 06:16:04 +00:00

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
This commit is contained in:
mat 2022-08-06 07:22:19 +00:00 committed by GitHub
parent 1d48c3fe34
commit 5a9fca0ca9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
55 changed files with 589 additions and 382 deletions

20
Cargo.lock generated
View file

@ -19,6 +19,12 @@ dependencies = [
"cpufeatures", "cpufeatures",
] ]
[[package]]
name = "anyhow"
version = "1.0.59"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c91f1f46651137be86f3a2b9a8359f9ab421d04d941c62b5982e1ca21113adf9"
[[package]] [[package]]
name = "async-compression" name = "async-compression"
version = "0.3.14" version = "0.3.14"
@ -75,6 +81,7 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
name = "azalea-auth" name = "azalea-auth"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"azalea-buf",
"uuid", "uuid",
] ]
@ -95,6 +102,8 @@ version = "0.1.0"
dependencies = [ dependencies = [
"buf-macros", "buf-macros",
"byteorder", "byteorder",
"serde_json",
"thiserror",
"tokio", "tokio",
"uuid", "uuid",
] ]
@ -114,12 +123,14 @@ dependencies = [
name = "azalea-client" name = "azalea-client"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"anyhow",
"azalea-auth", "azalea-auth",
"azalea-core", "azalea-core",
"azalea-crypto", "azalea-crypto",
"azalea-entity", "azalea-entity",
"azalea-protocol", "azalea-protocol",
"azalea-world", "azalea-world",
"thiserror",
"tokio", "tokio",
"uuid", "uuid",
] ]
@ -218,6 +229,7 @@ dependencies = [
"azalea-nbt", "azalea-nbt",
"log", "log",
"nohash-hasher", "nohash-hasher",
"thiserror",
"uuid", "uuid",
] ]
@ -1290,18 +1302,18 @@ dependencies = [
[[package]] [[package]]
name = "thiserror" name = "thiserror"
version = "1.0.31" version = "1.0.32"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd829fe32373d27f76265620b5309d0340cb8550f523c1dda251d6298069069a" checksum = "f5f6586b7f764adc0231f4c79be7b920e766bb2f3e51b3661cdb263828f19994"
dependencies = [ dependencies = [
"thiserror-impl", "thiserror-impl",
] ]
[[package]] [[package]]
name = "thiserror-impl" name = "thiserror-impl"
version = "1.0.31" version = "1.0.32"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0396bc89e626244658bef819e22d0cc459e795a5ebe878e6ec336d1674a8d79a" checksum = "12bafc5b54507e0149cdf1b145a5d80ab80a90bcd9275df43d4fff68460f6c21"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",

View file

@ -6,4 +6,5 @@ version = "0.1.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
azalea-buf = {path = "../azalea-buf"}
uuid = "1.1.2" uuid = "1.1.2"

View file

@ -1,12 +1,12 @@
use azalea_buf::McBuf;
use std::collections::HashMap; use std::collections::HashMap;
use uuid::Uuid; use uuid::Uuid;
#[derive(Clone, Debug)] #[derive(McBuf, Debug, Clone)]
pub struct GameProfile { pub struct GameProfile {
pub uuid: Uuid, pub uuid: Uuid,
pub name: String, pub name: String,
pub properties: HashMap<String, String>, pub properties: HashMap<String, ProfilePropertyValue>,
} }
impl GameProfile { impl GameProfile {
@ -18,3 +18,9 @@ impl GameProfile {
} }
} }
} }
#[derive(McBuf, Debug, Clone)]
pub struct ProfilePropertyValue {
pub value: String,
pub signature: Option<String>,
}

View file

@ -7,6 +7,11 @@ version = "0.1.0"
[dependencies] [dependencies]
buf-macros = {path = "./buf-macros"} 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"]} tokio = {version = "^1.19.2", features = ["io-util", "net", "macros"]}
uuid = "1.1.2" uuid = "^1.1.2"
[features]
serde_json = ["dep:serde_json"]

View file

@ -10,4 +10,4 @@ proc-macro = true
[dependencies] [dependencies]
proc-macro2 = "^1.0.36" proc-macro2 = "^1.0.36"
quote = "^1.0.10" quote = "^1.0.10"
syn = "^1.0.82" syn = {version = "^1.0.82", features = ["extra-traits"]}

View file

@ -41,7 +41,7 @@ fn create_impl_mcbufreadable(ident: &Ident, data: &Data) -> proc_macro2::TokenSt
quote! { quote! {
impl azalea_buf::McBufReadable for #ident { 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)* #(#read_fields)*
Ok(#ident { Ok(#ident {
#(#read_field_names: #read_field_names),* #(#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 { variant_discrim = match &d.1 {
syn::Expr::Lit(e) => match &e.lit { syn::Expr::Lit(e) => match &e.lit {
syn::Lit::Int(i) => i.base10_parse().unwrap(), 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 => { None => {
@ -76,12 +81,12 @@ fn create_impl_mcbufreadable(ident: &Ident, data: &Data) -> proc_macro2::TokenSt
quote! { quote! {
impl azalea_buf::McBufReadable for #ident { 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)?; let id = azalea_buf::McBufVarReadable::var_read_from(buf)?;
match id { match id {
#match_contents #match_contents
_ => Err(format!("Unknown enum variant {}", id)), _ => Err(azalea_buf::BufReadError::UnexpectedEnumVariant { id: id as i32 }),
} }
} }
} }

View file

@ -1,4 +1,4 @@
use crate::{McBufReadable, McBufWritable}; use crate::{read::BufReadError, McBufReadable, McBufWritable};
use std::{ use std::{
io::{Read, Write}, io::{Read, Write},
ops::Deref, ops::Deref,
@ -42,7 +42,7 @@ impl BitSet {
} }
impl McBufReadable for 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 { Ok(Self {
data: Vec::<u64>::read_from(buf)?, data: Vec::<u64>::read_from(buf)?,
}) })

View file

@ -9,7 +9,7 @@ mod write;
pub use buf_macros::*; pub use buf_macros::*;
pub use definitions::*; 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 serializable_uuid::*;
pub use write::{McBufVarWritable, McBufWritable, Writable}; pub use write::{McBufVarWritable, McBufWritable, Writable};

View file

@ -1,34 +1,62 @@
use super::{UnsizedByteArray, MAX_STRING_LENGTH}; use super::{UnsizedByteArray, MAX_STRING_LENGTH};
use byteorder::{ReadBytesExt, BE}; use byteorder::{ReadBytesExt, BE};
use std::{collections::HashMap, hash::Hash, io::Read}; use std::{collections::HashMap, hash::Hash, io::Read};
use thiserror::Error;
use tokio::io::{AsyncRead, AsyncReadExt}; 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 // TODO: get rid of Readable and use McBufReadable everywhere
pub trait Readable { pub trait Readable {
fn read_int_id_list(&mut self) -> Result<Vec<i32>, String>; fn read_int_id_list(&mut self) -> Result<Vec<i32>, BufReadError>;
fn read_varint(&mut self) -> Result<i32, String>; fn read_varint(&mut self) -> Result<i32, BufReadError>;
fn get_varint_size(&mut self, value: i32) -> u8; fn get_varint_size(&mut self, value: i32) -> u8;
fn get_varlong_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_byte_array(&mut self) -> Result<Vec<u8>, BufReadError>;
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>;
fn read_bytes(&mut self) -> Result<Vec<u8>, String>; fn read_bytes(&mut self) -> Result<Vec<u8>, BufReadError>;
fn read_utf(&mut self) -> Result<String, String>; fn read_utf(&mut self) -> Result<String, BufReadError>;
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>;
fn read_byte(&mut self) -> Result<u8, String>; fn read_byte(&mut self) -> Result<u8, BufReadError>;
fn read_int(&mut self) -> Result<i32, String>; fn read_int(&mut self) -> Result<i32, BufReadError>;
fn read_boolean(&mut self) -> Result<bool, String>; fn read_boolean(&mut self) -> Result<bool, BufReadError>;
fn read_long(&mut self) -> Result<i64, String>; fn read_long(&mut self) -> Result<i64, BufReadError>;
fn read_short(&mut self) -> Result<i16, String>; fn read_short(&mut self) -> Result<i16, BufReadError>;
fn read_float(&mut self) -> Result<f32, String>; fn read_float(&mut self) -> Result<f32, BufReadError>;
fn read_double(&mut self) -> Result<f64, String>; fn read_double(&mut self) -> Result<f64, BufReadError>;
} }
impl<R> Readable for R impl<R> Readable for R
where where
R: Read, 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 len = self.read_varint()?;
let mut list = Vec::with_capacity(len as usize); let mut list = Vec::with_capacity(len as usize);
for _ in 0..len { 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 // 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 /// 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 buffer = [0];
let mut ans = 0; let mut ans = 0;
for i in 0..5 { for i in 0..5 {
self.read_exact(&mut buffer) self.read_exact(&mut buffer)
.map_err(|_| "Invalid VarInt".to_string())?; .map_err(|_| BufReadError::InvalidVarInt)?;
ans |= ((buffer[0] & 0b0111_1111) as i32) << (7 * i); ans |= ((buffer[0] & 0b0111_1111) as i32) << (7 * i);
if buffer[0] & 0b1000_0000 == 0 { if buffer[0] & 0b1000_0000 == 0 {
return Ok(ans); return Ok(ans);
@ -73,122 +101,102 @@ where
10 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; let length = self.read_varint()? as usize;
self.read_bytes_with_len(length) 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]; let mut buffer = vec![0; n];
self.read_exact(&mut buffer) self.read_exact(&mut buffer)
.map_err(|_| "Error reading bytes".to_string())?; .map_err(|_| BufReadError::CouldNotReadBytes)?;
Ok(buffer) 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 // read to end of the buffer
let mut bytes = vec![]; let mut bytes = vec![];
self.read_to_end(&mut bytes) self.read_to_end(&mut bytes)
.map_err(|_| "Error reading bytes".to_string())?; .map_err(|_| BufReadError::CouldNotReadBytes)?;
Ok(bytes) 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()) 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()?; 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 // i don't know why it's multiplied by 4 but it's like that in mojang's code so
if length < 0 { if length < 0 {
return Err( return Err(BufReadError::StringLengthLessThanZero);
"The received encoded string buffer length is less than zero! Weird string!"
.to_string(),
);
} }
if length as u32 > max_length * 4 { if length as u32 > max_length * 4 {
return Err(format!( return Err(BufReadError::StringLengthTooLong {
"The received encoded string buffer length is longer than maximum allowed ({} > {})",
length, length,
max_length * 4 max_length: max_length * 4,
)); });
} }
// this is probably quite inefficient, idk how to do it better // this is probably quite inefficient, idk how to do it better
let mut string = String::new(); let mut string = String::new();
let mut buffer = vec![0; length as usize]; let mut buffer = vec![0; length as usize];
self.read_exact(&mut buffer) 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()); string.push_str(std::str::from_utf8(&buffer).unwrap());
if string.len() > length as usize { if string.len() > length as usize {
return Err(format!( return Err(BufReadError::StringLengthTooLong { length, max_length });
"The received string length is longer than maximum allowed ({} > {})",
length, max_length
));
} }
Ok(string) Ok(string)
} }
/// Read a single byte from the reader /// Read a single byte from the reader
fn read_byte(&mut self) -> Result<u8, String> { fn read_byte(&mut self) -> Result<u8, BufReadError> {
self.read_u8().map_err(|_| "Error reading byte".to_string()) Ok(self.read_u8()?)
} }
fn read_int(&mut self) -> Result<i32, String> { fn read_int(&mut self) -> Result<i32, BufReadError> {
match self.read_i32::<BE>() { Ok(self.read_i32::<BE>()?)
Ok(r) => Ok(r),
Err(_) => Err("Error reading int".to_string()),
}
} }
fn read_boolean(&mut self) -> Result<bool, String> { fn read_boolean(&mut self) -> Result<bool, BufReadError> {
match self.read_byte()? { match self.read_byte()? {
0 => Ok(false), 0 => Ok(false),
1 => Ok(true), 1 => Ok(true),
_ => Err("Error reading boolean".to_string()), _ => Err(BufReadError::InvalidBoolean),
} }
} }
fn read_long(&mut self) -> Result<i64, String> { fn read_long(&mut self) -> Result<i64, BufReadError> {
match self.read_i64::<BE>() { Ok(self.read_i64::<BE>()?)
Ok(r) => Ok(r),
Err(_) => Err("Error reading long".to_string()),
}
} }
fn read_short(&mut self) -> Result<i16, String> { fn read_short(&mut self) -> Result<i16, BufReadError> {
match self.read_i16::<BE>() { Ok(self.read_i16::<BE>()?)
Ok(r) => Ok(r),
Err(_) => Err("Error reading short".to_string()),
}
} }
fn read_float(&mut self) -> Result<f32, String> { fn read_float(&mut self) -> Result<f32, BufReadError> {
match self.read_f32::<BE>() { Ok(self.read_f32::<BE>()?)
Ok(r) => Ok(r),
Err(_) => Err("Error reading float".to_string()),
}
} }
fn read_double(&mut self) -> Result<f64, String> { fn read_double(&mut self) -> Result<f64, BufReadError> {
match self.read_f64::<BE>() { Ok(self.read_f64::<BE>()?)
Ok(r) => Ok(r),
Err(_) => Err("Error reading double".to_string()),
}
} }
} }
// fast varints modified from https://github.com/luojia65/mc-varint/blob/master/src/lib.rs#L67 // 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 /// 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 buffer = [0];
let mut ans = 0; let mut ans = 0;
for i in 0..5 { for i in 0..5 {
reader reader
.read_exact(&mut buffer) .read_exact(&mut buffer)
.await .await
.map_err(|_| "Invalid VarInt".to_string())?; .map_err(|_| BufReadError::InvalidVarInt)?;
ans |= ((buffer[0] & 0b0111_1111) as i32) << (7 * i); ans |= ((buffer[0] & 0b0111_1111) as i32) << (7 * i);
if buffer[0] & 0b1000_0000 == 0 { if buffer[0] & 0b1000_0000 == 0 {
return Ok(ans); return Ok(ans);
@ -201,36 +209,36 @@ pub trait McBufReadable
where where
Self: Sized, 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 pub trait McBufVarReadable
where where
Self: Sized, 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 { 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) Readable::read_int(buf)
} }
} }
impl McBufVarReadable for i32 { 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() buf.read_varint()
} }
} }
impl McBufVarReadable for i64 { impl McBufVarReadable for i64 {
// fast varints modified from https://github.com/luojia65/mc-varint/blob/master/src/lib.rs#L54 // 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 buffer = [0];
let mut ans = 0; let mut ans = 0;
for i in 0..8 { for i in 0..8 {
buf.read_exact(&mut buffer) buf.read_exact(&mut buffer)
.map_err(|_| "Invalid VarLong".to_string())?; .map_err(|_| BufReadError::InvalidVarLong)?;
ans |= ((buffer[0] & 0b0111_1111) as i64) << (7 * i); ans |= ((buffer[0] & 0b0111_1111) as i64) << (7 * i);
if buffer[0] & 0b1000_0000 == 0 { if buffer[0] & 0b1000_0000 == 0 {
break; break;
@ -240,19 +248,19 @@ impl McBufVarReadable for i64 {
} }
} }
impl McBufVarReadable for u64 { 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) i64::var_read_from(buf).map(|i| i as u64)
} }
} }
impl McBufReadable for UnsizedByteArray { 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()) Ok(buf.read_bytes()?.into())
} }
} }
impl<T: McBufReadable + Send> McBufReadable for Vec<T> { 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 length = buf.read_varint()? as usize;
let mut contents = Vec::with_capacity(length); let mut contents = Vec::with_capacity(length);
for _ in 0..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> { 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 length = buf.read_varint()? as usize;
let mut contents = HashMap::with_capacity(length); let mut contents = HashMap::with_capacity(length);
for _ in 0..length { for _ in 0..length {
@ -274,49 +282,49 @@ impl<K: McBufReadable + Send + Eq + Hash, V: McBufReadable + Send> McBufReadable
} }
impl McBufReadable for Vec<u8> { 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() buf.read_byte_array()
} }
} }
impl McBufReadable for String { 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() buf.read_utf()
} }
} }
impl McBufReadable for u32 { 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) Readable::read_int(buf).map(|i| i as u32)
} }
} }
impl McBufVarReadable for 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) buf.read_varint().map(|i| i as u32)
} }
} }
impl McBufReadable for u16 { 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) buf.read_short().map(|i| i as u16)
} }
} }
impl McBufReadable for i16 { 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() buf.read_short()
} }
} }
impl McBufVarReadable for u16 { 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) buf.read_varint().map(|i| i as u16)
} }
} }
impl<T: McBufVarReadable> McBufVarReadable for Vec<T> { 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 length = buf.read_varint()? as usize;
let mut contents = Vec::with_capacity(length); let mut contents = Vec::with_capacity(length);
for _ in 0..length { for _ in 0..length {
@ -327,49 +335,49 @@ impl<T: McBufVarReadable> McBufVarReadable for Vec<T> {
} }
impl McBufReadable for i64 { 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() buf.read_long()
} }
} }
impl McBufReadable for u64 { 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) i64::read_from(buf).map(|i| i as u64)
} }
} }
impl McBufReadable for bool { 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() buf.read_boolean()
} }
} }
impl McBufReadable for u8 { 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() buf.read_byte()
} }
} }
impl McBufReadable for i8 { 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) buf.read_byte().map(|i| i as i8)
} }
} }
impl McBufReadable for f32 { 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() buf.read_float()
} }
} }
impl McBufReadable for f64 { 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() buf.read_double()
} }
} }
impl<T: McBufReadable> McBufReadable for Option<T> { 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()?; let present = buf.read_boolean()?;
Ok(if present { Ok(if present {
Some(T::read_from(buf)?) Some(T::read_from(buf)?)

View file

@ -1,4 +1,4 @@
use crate::{McBufReadable, McBufWritable, Readable}; use crate::{read::BufReadError, McBufReadable, McBufWritable, Readable};
use std::io::{Read, Write}; use std::io::{Read, Write};
use uuid::Uuid; use uuid::Uuid;
@ -33,7 +33,7 @@ impl SerializableUuid for Uuid {
} }
impl McBufReadable 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([ Ok(Uuid::from_int_array([
Readable::read_int(buf)? as u32, Readable::read_int(buf)? as u32,
Readable::read_int(buf)? as u32, Readable::read_int(buf)? as u32,

View file

@ -6,7 +6,7 @@ version = "0.1.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
azalea-buf = {path = "../azalea-buf"} azalea-buf = {path = "../azalea-buf", features = ["serde_json"]}
azalea-language = {path = "../azalea-language"} azalea-language = {path = "../azalea-language"}
lazy_static = "1.4.0" lazy_static = "1.4.0"
serde = "^1.0.130" serde = "^1.0.130"

View file

@ -1,6 +1,6 @@
use std::io::{Read, Write}; use std::io::{Read, Write};
use azalea_buf::{McBufReadable, McBufWritable}; use azalea_buf::{BufReadError, McBufReadable, McBufWritable};
use serde::{de, Deserialize, Deserializer}; use serde::{de, Deserialize, Deserializer};
use crate::{ use crate::{
@ -269,11 +269,10 @@ impl<'de> Deserialize<'de> for Component {
} }
impl McBufReadable 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 string = String::read_from(buf)?;
let json: serde_json::Value = serde_json::from_str(string.as_str()) 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)?;
let component = Component::deserialize(json).map_err(|e| e.to_string())?;
Ok(component) Ok(component)
} }
} }

View file

@ -9,17 +9,17 @@ pub struct TextColor {
} }
impl TextColor { impl TextColor {
pub fn parse(value: String) -> Result<TextColor, String> { pub fn parse(value: String) -> Option<TextColor> {
if value.starts_with('#') { if value.starts_with('#') {
let n = value.chars().skip(1).collect::<String>(); let n = value.chars().skip(1).collect::<String>();
let n = u32::from_str_radix(&n, 16).unwrap(); 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()); let color_option = NAMED_COLORS.get(&value.to_ascii_uppercase());
if let Some(color) = color_option { 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 { 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 { for formatter in &ChatFormatting::FORMATTERS {
if formatter.code == code { 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 let color: Option<TextColor> = json_object
.get("color") .get("color")
.and_then(|v| v.as_str()) .and_then(|v| v.as_str())
.and_then(|v| TextColor::parse(v.to_string()).ok()); .and_then(|v| TextColor::parse(v.to_string()));
Style { Style {
color, color,
bold, bold,

View file

@ -22,7 +22,7 @@ pub fn legacy_color_code_to_text_component(legacy_color_code: &str) -> TextCompo
while i < legacy_color_code.chars().count() { while i < legacy_color_code.chars().count() {
if legacy_color_code.chars().nth(i).unwrap() == LEGACY_FORMATTING_CODE_SYMBOL { if legacy_color_code.chars().nth(i).unwrap() == LEGACY_FORMATTING_CODE_SYMBOL {
let formatting_code = legacy_color_code.chars().nth(i + 1).unwrap(); 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() { if components.is_empty() || !components.last().unwrap().text.is_empty() {
components.push(TextComponent::new("".to_string())); components.push(TextComponent::new("".to_string()));
} }

View file

@ -6,11 +6,13 @@ version = "0.1.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
anyhow = "1.0.59"
azalea-auth = {path = "../azalea-auth"} azalea-auth = {path = "../azalea-auth"}
azalea-core = {path = "../azalea-core"} azalea-core = {path = "../azalea-core"}
azalea-crypto = {path = "../azalea-crypto"} azalea-crypto = {path = "../azalea-crypto"}
azalea-entity = {path = "../azalea-entity"} azalea-entity = {path = "../azalea-entity"}
azalea-protocol = {path = "../azalea-protocol"} azalea-protocol = {path = "../azalea-protocol"}
azalea-world = {path = "../azalea-world"} azalea-world = {path = "../azalea-world"}
tokio = {version = "1.19.2", features = ["sync"]} thiserror = "^1.0.32"
uuid = "1.1.2" tokio = {version = "^1.19.2", features = ["sync"]}
uuid = "^1.1.2"

View file

@ -1,6 +1,6 @@
//! Connect to Minecraft servers. //! Connect to Minecraft servers.
use crate::{Client, Event}; use crate::{client::JoinError, Client, Event};
use azalea_protocol::ServerAddress; use azalea_protocol::ServerAddress;
use tokio::sync::mpsc::UnboundedReceiver; use tokio::sync::mpsc::UnboundedReceiver;
@ -19,7 +19,7 @@ impl Account {
pub async fn join( pub async fn join(
&self, &self,
address: &ServerAddress, address: &ServerAddress,
) -> Result<(Client, UnboundedReceiver<Event>), String> { ) -> Result<(Client, UnboundedReceiver<Event>), JoinError> {
Client::join(self, address).await Client::join(self, address).await
} }
} }

View file

@ -3,7 +3,7 @@ use azalea_auth::game_profile::GameProfile;
use azalea_core::{ChunkPos, EntityPos, PositionDelta, PositionDeltaTrait, ResourceLocation}; use azalea_core::{ChunkPos, EntityPos, PositionDelta, PositionDeltaTrait, ResourceLocation};
use azalea_entity::Entity; use azalea_entity::Entity;
use azalea_protocol::{ use azalea_protocol::{
connect::Connection, connect::{Connection, ConnectionError},
packets::{ packets::{
game::{ game::{
clientbound_player_chat_packet::ClientboundPlayerChatPacket, clientbound_player_chat_packet::ClientboundPlayerChatPacket,
@ -22,13 +22,16 @@ use azalea_protocol::{
}, },
ConnectionProtocol, PROTOCOL_VERSION, ConnectionProtocol, PROTOCOL_VERSION,
}, },
read::ReadPacketError,
resolver, ServerAddress, resolver, ServerAddress,
}; };
use azalea_world::Dimension; use azalea_world::Dimension;
use std::{ use std::{
fmt::Debug, fmt::Debug,
io,
sync::{Arc, Mutex}, sync::{Arc, Mutex},
}; };
use thiserror::Error;
use tokio::{ use tokio::{
sync::mpsc::{self, UnboundedReceiver, UnboundedSender}, sync::mpsc::{self, UnboundedReceiver, UnboundedSender},
time::{self}, time::{self},
@ -70,15 +73,34 @@ pub struct Client {
/// Whether we should ignore errors when decoding packets. /// Whether we should ignore errors when decoding packets.
const IGNORE_ERRORS: bool = !cfg!(debug_assertions); const IGNORE_ERRORS: bool = !cfg!(debug_assertions);
#[derive(Debug)] #[derive(Error, Debug)]
struct HandleError(String); 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 { impl Client {
/// Connect to a Minecraft server with an account. /// Connect to a Minecraft server with an account.
pub async fn join( pub async fn join(
account: &Account, account: &Account,
address: &ServerAddress, address: &ServerAddress,
) -> Result<(Self, UnboundedReceiver<Event>), String> { ) -> Result<(Self, UnboundedReceiver<Event>), JoinError> {
let resolved_address = resolver::resolve_address(address).await?; let resolved_address = resolver::resolve_address(address).await?;
let mut conn = Connection::new(&resolved_address).await?; let mut conn = Connection::new(&resolved_address).await?;
@ -93,7 +115,7 @@ impl Client {
} }
.get(), .get(),
) )
.await; .await?;
let mut conn = conn.login(); let mut conn = conn.login();
// login // login
@ -105,7 +127,7 @@ impl Client {
} }
.get(), .get(),
) )
.await; .await?;
let (conn, game_profile) = loop { let (conn, game_profile) = loop {
let packet_result = conn.read().await; let packet_result = conn.read().await;
@ -126,7 +148,7 @@ impl Client {
} }
.get(), .get(),
) )
.await; .await?;
conn.set_encryption_key(e.secret_key); conn.set_encryption_key(e.secret_key);
} }
ClientboundLoginPacket::ClientboundLoginCompressionPacket(p) => { ClientboundLoginPacket::ClientboundLoginCompressionPacket(p) => {
@ -180,22 +202,23 @@ impl Client {
Ok(packet) => match Self::handle(&packet, &client, &tx).await { Ok(packet) => match Self::handle(&packet, &client, &tx).await {
Ok(_) => {} Ok(_) => {}
Err(e) => { Err(e) => {
println!("Error handling packet: {:?}", e); println!("Error handling packet: {}", e);
if IGNORE_ERRORS { if IGNORE_ERRORS {
continue; continue;
} else { } else {
panic!("Error handling packet: {:?}", e); panic!("Error handling packet: {}", e);
} }
} }
}, },
Err(e) => { Err(e) => {
if IGNORE_ERRORS { if IGNORE_ERRORS {
println!("Error: {:?}", e); println!("{}", e);
if e == "length wider than 21-bit" { match e {
panic!(); ReadPacketError::FrameSplitter { .. } => panic!("Error: {:?}", e),
_ => continue,
} }
} else { } else {
panic!("Error: {:?}", e); panic!("{}", e);
} }
} }
}; };
@ -303,7 +326,7 @@ impl Client {
} }
.get(), .get(),
) )
.await; .await?;
tx.send(Event::Login).unwrap(); tx.send(Event::Login).unwrap();
} }
@ -416,7 +439,7 @@ impl Client {
let mut conn_lock = client.conn.lock().await; let mut conn_lock = client.conn.lock().await;
conn_lock conn_lock
.write(ServerboundAcceptTeleportationPacket { id: p.id }.get()) .write(ServerboundAcceptTeleportationPacket { id: p.id }.get())
.await; .await?;
conn_lock conn_lock
.write( .write(
ServerboundMovePlayerPacketPosRot { ServerboundMovePlayerPacketPosRot {
@ -430,7 +453,7 @@ impl Client {
} }
.get(), .get(),
) )
.await; .await?;
} }
ClientboundGamePacket::ClientboundPlayerInfoPacket(p) => { ClientboundGamePacket::ClientboundPlayerInfoPacket(p) => {
println!("Got player info packet {:?}", p); println!("Got player info packet {:?}", p);
@ -514,14 +537,16 @@ impl Client {
let mut dimension_lock = client.dimension.lock()?; let mut dimension_lock = client.dimension.lock()?;
let dimension = dimension_lock.as_mut().unwrap(); let dimension = dimension_lock.as_mut().unwrap();
dimension.move_entity( dimension
p.id, .move_entity(
EntityPos { p.id,
x: p.x, EntityPos {
y: p.y, x: p.x,
z: p.z, y: p.y,
}, z: p.z,
)?; },
)
.map_err(|e| HandleError::Other(e.into()))?;
} }
ClientboundGamePacket::ClientboundUpdateAdvancementsPacket(p) => { ClientboundGamePacket::ClientboundUpdateAdvancementsPacket(p) => {
println!("Got update advancements packet {:?}", p); println!("Got update advancements packet {:?}", p);
@ -533,13 +558,17 @@ impl Client {
let mut dimension_lock = client.dimension.lock()?; let mut dimension_lock = client.dimension.lock()?;
let dimension = dimension_lock.as_mut().unwrap(); 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) => { ClientboundGamePacket::ClientboundMoveEntityPosrotPacket(p) => {
let mut dimension_lock = client.dimension.lock()?; let mut dimension_lock = client.dimension.lock()?;
let dimension = dimension_lock.as_mut().unwrap(); 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) => { ClientboundGamePacket::ClientboundMoveEntityRotPacket(p) => {
println!("Got move entity rot packet {:?}", p); println!("Got move entity rot packet {:?}", p);
@ -551,7 +580,7 @@ impl Client {
.lock() .lock()
.await .await
.write(ServerboundKeepAlivePacket { id: p.id }.get()) .write(ServerboundKeepAlivePacket { id: p.id }.get())
.await; .await?;
} }
ClientboundGamePacket::ClientboundRemoveEntitiesPacket(p) => { ClientboundGamePacket::ClientboundRemoveEntitiesPacket(p) => {
println!("Got remove entities packet {:?}", p); println!("Got remove entities packet {:?}", p);
@ -625,12 +654,6 @@ impl Client {
impl<T> From<std::sync::PoisonError<T>> for HandleError { impl<T> From<std::sync::PoisonError<T>> for HandleError {
fn from(e: std::sync::PoisonError<T>) -> Self { fn from(e: std::sync::PoisonError<T>) -> Self {
HandleError(e.to_string()) HandleError::Poison(e.to_string())
}
}
impl From<String> for HandleError {
fn from(e: String) -> Self {
HandleError(e)
} }
} }

View file

@ -1,10 +1,20 @@
use crate::Client; use crate::Client;
use azalea_core::EntityPos; use azalea_core::EntityPos;
use azalea_protocol::packets::game::serverbound_move_player_packet_pos_rot::ServerboundMovePlayerPacketPosRot; 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 { impl Client {
/// Set the client's position to the given coordinates. /// 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 mut dimension_lock = self.dimension.lock().unwrap();
let dimension = dimension_lock.as_mut().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) { let player_id = if let Some(player_lock) = player_lock.entity(dimension) {
player_lock.id player_lock.id
} else { } 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 self.conn
@ -34,7 +49,7 @@ impl Client {
} }
.get(), .get(),
) )
.await; .await?;
Ok(()) Ok(())
} }

View file

@ -1,6 +1,6 @@
///! Ping Minecraft servers. ///! Ping Minecraft servers.
use azalea_protocol::{ use azalea_protocol::{
connect::Connection, connect::{Connection, ConnectionError},
packets::{ packets::{
handshake::client_intention_packet::ClientIntentionPacket, handshake::client_intention_packet::ClientIntentionPacket,
status::{ status::{
@ -12,10 +12,24 @@ use azalea_protocol::{
}, },
resolver, ServerAddress, 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( pub async fn ping_server(
address: &ServerAddress, address: &ServerAddress,
) -> Result<ClientboundStatusResponsePacket, String> { ) -> Result<ClientboundStatusResponsePacket, PingError> {
let resolved_address = resolver::resolve_address(address).await?; let resolved_address = resolver::resolve_address(address).await?;
let mut conn = Connection::new(&resolved_address).await?; let mut conn = Connection::new(&resolved_address).await?;
@ -30,13 +44,13 @@ pub async fn ping_server(
} }
.get(), .get(),
) )
.await; .await?;
let mut conn = conn.status(); let mut conn = conn.status();
// send the empty status request packet // 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 { match packet {
ClientboundStatusPacket::ClientboundStatusResponsePacket(p) => Ok(p), ClientboundStatusPacket::ClientboundStatusResponsePacket(p) => Ok(p),

View file

@ -3,7 +3,7 @@ use std::{
io::{Read, Write}, io::{Read, Write},
}; };
use azalea_buf::{McBufReadable, McBufWritable}; use azalea_buf::{BufReadError, McBufReadable, McBufWritable};
#[derive(Hash, Clone, Debug, PartialEq, Eq)] #[derive(Hash, Clone, Debug, PartialEq, Eq)]
pub enum Difficulty { pub enum Difficulty {
@ -67,7 +67,7 @@ impl Difficulty {
} }
impl McBufReadable for 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)?)) Ok(Difficulty::by_id(u8::read_from(buf)?))
} }
} }

View file

@ -1,4 +1,4 @@
use azalea_buf::{McBufReadable, McBufWritable}; use azalea_buf::{BufReadError, McBufReadable, McBufWritable};
use std::io::{Read, Write}; use std::io::{Read, Write};
#[derive(Hash, Copy, Clone, Debug)] #[derive(Hash, Copy, Clone, Debug)]
@ -27,22 +27,24 @@ impl GameType {
} }
} }
pub fn from_id(id: u8) -> Result<GameType, String> { pub fn from_id(id: u8) -> Option<GameType> {
Ok(match id { Some(match id {
0 => GameType::SURVIVAL, 0 => GameType::SURVIVAL,
1 => GameType::CREATIVE, 1 => GameType::CREATIVE,
2 => GameType::ADVENTURE, 2 => GameType::ADVENTURE,
3 => GameType::SPECTATOR, 3 => GameType::SPECTATOR,
_ => return Err(format!("Unknown game type id: {}", id)), _ => return None,
}) })
} }
pub fn from_optional_id(id: i8) -> Result<OptionalGameType, String> { pub fn from_optional_id(id: i8) -> Option<OptionalGameType> {
Ok(match id { Some(
-1 => None, match id {
id => Some(GameType::from_id(id as u8)?), -1 => None,
} id => Some(GameType::from_id(id as u8)?),
.into()) }
.into(),
)
} }
pub fn short_name(&self) -> &'static str { pub fn short_name(&self) -> &'static str {
@ -77,8 +79,9 @@ impl GameType {
} }
impl McBufReadable for GameType { impl McBufReadable for GameType {
fn read_from(buf: &mut impl Read) -> Result<Self, String> { fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
GameType::from_id(u8::read_from(buf)?) 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 { impl McBufReadable for OptionalGameType {
fn read_from(buf: &mut impl Read) -> Result<Self, String> { fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
GameType::from_optional_id(i8::read_from(buf)?) let id = i8::read_from(buf)?;
GameType::from_optional_id(id)
.ok_or_else(|| BufReadError::UnexpectedEnumVariant { id: id as i32 })
} }
} }

View file

@ -1,5 +1,5 @@
use crate::{BlockPos, Slot}; use crate::{BlockPos, Slot};
use azalea_buf::{McBuf, McBufReadable, McBufVarReadable, McBufWritable}; use azalea_buf::{BufReadError, McBuf, McBufReadable, McBufVarReadable, McBufWritable};
use std::io::{Read, Write}; use std::io::{Read, Write};
#[derive(Debug, Clone, McBuf)] #[derive(Debug, Clone, McBuf)]
@ -153,7 +153,7 @@ pub struct VibrationParticle {
} }
impl ParticleData { 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 { Ok(match id {
0 => ParticleData::AmbientEntityEffect, 0 => ParticleData::AmbientEntityEffect,
1 => ParticleData::AngryVillager, 1 => ParticleData::AngryVillager,
@ -243,13 +243,13 @@ impl ParticleData {
85 => ParticleData::WaxOff, 85 => ParticleData::WaxOff,
86 => ParticleData::ElectricSpark, 86 => ParticleData::ElectricSpark,
87 => ParticleData::Scrape, 87 => ParticleData::Scrape,
_ => return Err(format!("Unknown particle id: {}", id)), _ => return Err(BufReadError::UnexpectedEnumVariant { id: id as i32 }),
}) })
} }
} }
impl McBufReadable for ParticleData { 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)?; let id = u32::var_read_from(buf)?;
ParticleData::read_from_particle_id(buf, id) ParticleData::read_from_particle_id(buf, id)
} }

View file

@ -1,5 +1,5 @@
use crate::ResourceLocation; use crate::ResourceLocation;
use azalea_buf::{McBufReadable, McBufWritable}; use azalea_buf::{BufReadError, McBufReadable, McBufWritable};
use std::{ use std::{
io::{Read, Write}, io::{Read, Write},
ops::Rem, ops::Rem,
@ -225,7 +225,7 @@ impl From<&EntityPos> for ChunkPos {
} }
impl McBufReadable for BlockPos { 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 val = u64::read_from(buf)?;
let x = (val >> 38) as i32; let x = (val >> 38) as i32;
let y = (val & 0xFFF) as i32; let y = (val & 0xFFF) as i32;
@ -235,7 +235,7 @@ impl McBufReadable for BlockPos {
} }
impl McBufReadable for GlobalPos { 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 { Ok(GlobalPos {
dimension: ResourceLocation::read_from(buf)?, dimension: ResourceLocation::read_from(buf)?,
pos: BlockPos::read_from(buf)?, pos: BlockPos::read_from(buf)?,
@ -244,7 +244,7 @@ impl McBufReadable for GlobalPos {
} }
impl McBufReadable for ChunkSectionPos { 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)?; let long = i64::read_from(buf)?;
Ok(ChunkSectionPos { Ok(ChunkSectionPos {
x: (long >> 42) as i32, x: (long >> 42) as i32,

View file

@ -1,6 +1,6 @@
//! A resource, like minecraft:stone //! A resource, like minecraft:stone
use azalea_buf::{McBufReadable, McBufWritable}; use azalea_buf::{BufReadError, McBufReadable, McBufWritable};
use std::io::{Read, Write}; use std::io::{Read, Write};
#[derive(Hash, Clone, PartialEq, Eq)] #[derive(Hash, Clone, PartialEq, Eq)]
@ -13,7 +13,7 @@ static DEFAULT_NAMESPACE: &str = "minecraft";
// static REALMS_NAMESPACE: &str = "realms"; // static REALMS_NAMESPACE: &str = "realms";
impl ResourceLocation { 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 sep_byte_position_option = resource_string.chars().position(|c| c == ':');
let (namespace, path) = if let Some(sep_byte_position) = sep_byte_position_option { let (namespace, path) = if let Some(sep_byte_position) = sep_byte_position_option {
if sep_byte_position == 0 { if sep_byte_position == 0 {
@ -46,7 +46,7 @@ impl std::fmt::Debug for ResourceLocation {
} }
impl McBufReadable 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)?; let location_string = String::read_from(buf)?;
ResourceLocation::new(&location_string) ResourceLocation::new(&location_string)
} }

View file

@ -1,6 +1,6 @@
// TODO: have an azalea-inventory or azalea-container crate and put this there // 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}; use std::io::{Read, Write};
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@ -18,7 +18,7 @@ pub struct SlotData {
} }
impl McBufReadable for Slot { 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)?; let present = bool::read_from(buf)?;
if !present { if !present {
return Ok(Slot::Empty); return Ok(Slot::Empty);

View file

@ -1,4 +1,4 @@
use azalea_buf::McBufVarReadable; use azalea_buf::{BufReadError, McBufVarReadable};
use azalea_buf::{McBuf, McBufReadable, McBufWritable}; use azalea_buf::{McBuf, McBufReadable, McBufWritable};
use azalea_chat::component::Component; use azalea_chat::component::Component;
use azalea_core::{BlockPos, Direction, Particle, Slot}; use azalea_core::{BlockPos, Direction, Particle, Slot};
@ -17,7 +17,7 @@ pub struct EntityDataItem {
} }
impl McBufReadable for EntityMetadata { 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(); let mut metadata = Vec::new();
loop { loop {
let index = u8::read_from(buf)?; let index = u8::read_from(buf)?;
@ -70,8 +70,8 @@ pub enum EntityDataValue {
} }
impl McBufReadable for EntityDataValue { impl McBufReadable for EntityDataValue {
fn read_from(buf: &mut impl Read) -> Result<Self, String> { fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
let data_type = i32::var_read_from(buf)?; let data_type = u32::var_read_from(buf)?;
Ok(match data_type { Ok(match data_type {
0 => EntityDataValue::Byte(u8::read_from(buf)?), 0 => EntityDataValue::Byte(u8::read_from(buf)?),
1 => EntityDataValue::Int(i32::var_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)?), 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,
})
}
}) })
} }
} }

View file

@ -1,5 +1,6 @@
use crate::Error; use crate::Error;
use crate::Tag; use crate::Tag;
use azalea_buf::BufReadError;
use azalea_buf::McBufReadable; use azalea_buf::McBufReadable;
use byteorder::{ReadBytesExt, BE}; use byteorder::{ReadBytesExt, BE};
use flate2::read::{GzDecoder, ZlibDecoder}; use flate2::read::{GzDecoder, ZlibDecoder};
@ -139,7 +140,7 @@ impl Tag {
} }
impl McBufReadable for 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) { match Tag::read(buf) {
Ok(r) => Ok(r), Ok(r) => Ok(r),
// Err(e) => Err(e.to_string()), // Err(e) => Err(e.to_string()),

View file

@ -22,7 +22,7 @@ flate2 = "1.0.23"
packet-macros = {path = "./packet-macros"} packet-macros = {path = "./packet-macros"}
serde = {version = "1.0.130", features = ["serde_derive"]} serde = {version = "1.0.130", features = ["serde_derive"]}
serde_json = "^1.0.72" serde_json = "^1.0.72"
thiserror = "^1.0.30" thiserror = "^1.0.32"
tokio = {version = "^1.19.2", features = ["io-util", "net", "macros"]} tokio = {version = "^1.19.2", features = ["io-util", "net", "macros"]}
tokio-util = "^0.6.9" tokio-util = "^0.6.9"
trust-dns-resolver = "^0.20.3" trust-dns-resolver = "^0.20.3"

33
azalea-protocol/packet-macros/src/lib.rs Executable file → Normal file
View file

@ -30,7 +30,7 @@ fn as_packet_derive(input: TokenStream, state: proc_macro2::TokenStream) -> Toke
pub fn read( pub fn read(
buf: &mut impl std::io::Read, buf: &mut impl std::io::Read,
) -> Result<#state, String> { ) -> Result<#state, azalea_buf::BufReadError> {
use azalea_buf::McBufReadable; use azalea_buf::McBufReadable;
Ok(Self::read_from(buf)?.get()) 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!(); let mut clientbound_read_match_contents = quote!();
for PacketIdPair { id, module, name } in input.serverbound.packets { 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! { serverbound_enum_contents.extend(quote! {
#name(#module::#name), #name(#module::#name),
}); });
@ -216,11 +217,19 @@ pub fn declare_state_packets(input: TokenStream) -> TokenStream {
#serverbound_state_name::#name(packet) => packet.write(buf), #serverbound_state_name::#name(packet) => packet.write(buf),
}); });
serverbound_read_match_contents.extend(quote! { 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 { 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! { clientbound_enum_contents.extend(quote! {
#name(#module::#name), #name(#module::#name),
}); });
@ -231,7 +240,15 @@ pub fn declare_state_packets(input: TokenStream) -> TokenStream {
#clientbound_state_name::#name(packet) => packet.write(buf), #clientbound_state_name::#name(packet) => packet.write(buf),
}); });
clientbound_read_match_contents.extend(quote! { 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( fn read(
id: u32, id: u32,
buf: &mut impl std::io::Read, buf: &mut impl std::io::Read,
) -> Result<#serverbound_state_name, String> ) -> Result<#serverbound_state_name, crate::read::ReadPacketError>
where where
Self: Sized, Self: Sized,
{ {
Ok(match id { Ok(match id {
#serverbound_read_match_contents #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( fn read(
id: u32, id: u32,
buf: &mut impl std::io::Read, buf: &mut impl std::io::Read,
) -> Result<#clientbound_state_name, String> ) -> Result<#clientbound_state_name, crate::read::ReadPacketError>
where where
Self: Sized, Self: Sized,
{ {
Ok(match id { Ok(match id {
#clientbound_read_match_contents #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 }),
}) })
} }
} }

View file

@ -5,12 +5,13 @@ use crate::packets::handshake::{ClientboundHandshakePacket, ServerboundHandshake
use crate::packets::login::{ClientboundLoginPacket, ServerboundLoginPacket}; use crate::packets::login::{ClientboundLoginPacket, ServerboundLoginPacket};
use crate::packets::status::{ClientboundStatusPacket, ServerboundStatusPacket}; use crate::packets::status::{ClientboundStatusPacket, ServerboundStatusPacket};
use crate::packets::ProtocolPacket; use crate::packets::ProtocolPacket;
use crate::read::read_packet; use crate::read::{read_packet, ReadPacketError};
use crate::write::write_packet; use crate::write::write_packet;
use crate::ServerIpAddress; use crate::ServerIpAddress;
use azalea_crypto::{Aes128CfbDec, Aes128CfbEnc}; use azalea_crypto::{Aes128CfbDec, Aes128CfbEnc};
use std::fmt::Debug; use std::fmt::Debug;
use std::marker::PhantomData; use std::marker::PhantomData;
use thiserror::Error;
use tokio::net::TcpStream; use tokio::net::TcpStream;
pub struct Connection<R: ProtocolPacket, W: ProtocolPacket> { pub struct Connection<R: ProtocolPacket, W: ProtocolPacket> {
@ -28,7 +29,7 @@ where
R: ProtocolPacket + Debug, R: ProtocolPacket + Debug,
W: 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, _>( read_packet::<R, _>(
&mut self.stream, &mut self.stream,
self.compression_threshold, self.compression_threshold,
@ -38,30 +39,32 @@ where
} }
/// Write a packet to the server /// 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( write_packet(
packet, packet,
&mut self.stream, &mut self.stream,
self.compression_threshold, self.compression_threshold,
&mut self.enc_cipher, &mut self.enc_cipher,
) )
.await; .await
} }
} }
#[derive(Error, Debug)]
pub enum ConnectionError {
#[error("{0}")]
Io(#[from] std::io::Error),
}
impl Connection<ClientboundHandshakePacket, ServerboundHandshakePacket> { 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 ip = address.ip;
let port = address.port; let port = address.port;
let stream = TcpStream::connect(format!("{}:{}", ip, port)) let stream = TcpStream::connect(format!("{}:{}", ip, port)).await?;
.await
.map_err(|_| "Failed to connect to server")?;
// enable tcp_nodelay // enable tcp_nodelay
stream stream.set_nodelay(true)?;
.set_nodelay(true)
.expect("Error enabling tcp_nodelay");
Ok(Connection { Ok(Connection {
stream, stream,

View file

@ -1,3 +1,4 @@
use azalea_buf::BufReadError;
use azalea_buf::McBuf; use azalea_buf::McBuf;
use azalea_buf::McBufVarReadable; use azalea_buf::McBufVarReadable;
use azalea_buf::{McBufReadable, McBufWritable, Readable, Writable}; use azalea_buf::{McBufReadable, McBufWritable, Readable, Writable};
@ -24,7 +25,7 @@ pub struct BrigadierNumber<T> {
max: Option<T>, max: Option<T>,
} }
impl<T: McBufReadable> McBufReadable for BrigadierNumber<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 flags = buf.read_byte()?;
let min = if flags & 0x01 != 0 { let min = if flags & 0x01 != 0 {
Some(T::read_from(buf)?) Some(T::read_from(buf)?)
@ -123,7 +124,7 @@ pub enum BrigadierParser {
} }
impl McBufReadable for 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)?; let parser_type = u32::var_read_from(buf)?;
match parser_type { match parser_type {
@ -190,14 +191,16 @@ impl McBufReadable for BrigadierParser {
45 => Ok(BrigadierParser::TemplateMirror), 45 => Ok(BrigadierParser::TemplateMirror),
46 => Ok(BrigadierParser::TemplateRotation), 46 => Ok(BrigadierParser::TemplateRotation),
47 => Ok(BrigadierParser::Uuid), 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 // TODO: BrigadierNodeStub should have more stuff
impl McBufReadable for BrigadierNodeStub { 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)?; let flags = u8::read_from(buf)?;
if flags > 31 { if flags > 31 {
println!( println!(

View file

@ -1,4 +1,4 @@
use azalea_buf::{McBufReadable, McBufVarReadable, McBufWritable}; use azalea_buf::{BufReadError, McBufReadable, McBufVarReadable, McBufWritable};
use azalea_core::ParticleData; use azalea_core::ParticleData;
use packet_macros::ClientboundGamePacket; use packet_macros::ClientboundGamePacket;
use std::io::{Read, Write}; use std::io::{Read, Write};
@ -20,7 +20,7 @@ pub struct ClientboundLevelParticlesPacket {
} }
impl McBufReadable for 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 particle_id = u32::var_read_from(buf)?;
let override_limiter = bool::read_from(buf)?; let override_limiter = bool::read_from(buf)?;
let x = f64::read_from(buf)?; let x = f64::read_from(buf)?;

View file

@ -1,4 +1,4 @@
use azalea_buf::McBuf; use azalea_buf::{BufReadError, McBuf};
use azalea_buf::{McBufReadable, McBufWritable, Readable}; use azalea_buf::{McBufReadable, McBufWritable, Readable};
use packet_macros::ClientboundGamePacket; use packet_macros::ClientboundGamePacket;
use std::io::{Read, Write}; use std::io::{Read, Write};
@ -20,7 +20,7 @@ pub struct PlayerAbilitiesFlags {
} }
impl McBufReadable for 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()?; let byte = buf.read_byte()?;
Ok(PlayerAbilitiesFlags { Ok(PlayerAbilitiesFlags {
invulnerable: byte & 1 != 0, invulnerable: byte & 1 != 0,

View file

@ -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_buf::{McBufVarReadable, McBufWritable};
use azalea_chat::component::Component; use azalea_chat::component::Component;
use azalea_crypto::{MessageSignature, SignedMessageHeader}; use azalea_crypto::{MessageSignature, SignedMessageHeader};
@ -74,13 +74,15 @@ pub enum FilterMask {
} }
impl McBufReadable for 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)?; let filter_mask = u32::var_read_from(buf)?;
match filter_mask { match filter_mask {
0 => Ok(FilterMask::PassThrough), 0 => Ok(FilterMask::PassThrough),
1 => Ok(FilterMask::FullyFiltered), 1 => Ok(FilterMask::FullyFiltered),
2 => Ok(FilterMask::PartiallyFiltered(BitSet::read_from(buf)?)), 2 => Ok(FilterMask::PartiallyFiltered(BitSet::read_from(buf)?)),
_ => Err("Invalid filter mask".to_string()), _ => Err(BufReadError::UnexpectedEnumVariant {
id: filter_mask as i32,
}),
} }
} }
} }

View file

@ -1,4 +1,4 @@
use azalea_buf::McBuf; use azalea_buf::{BufReadError, McBuf};
use azalea_buf::{McBufReadable, McBufWritable, Readable, Writable}; use azalea_buf::{McBufReadable, McBufWritable, Readable, Writable};
use azalea_chat::component::Component; use azalea_chat::component::Component;
use packet_macros::ClientboundGamePacket; use packet_macros::ClientboundGamePacket;
@ -63,7 +63,7 @@ pub struct RemovePlayer {
} }
impl McBufReadable for Action { 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()?; let id = buf.read_byte()?;
Ok(match id { Ok(match id {
0 => Action::AddPlayer(Vec::<AddPlayer>::read_from(buf)?), 0 => Action::AddPlayer(Vec::<AddPlayer>::read_from(buf)?),
@ -71,7 +71,7 @@ impl McBufReadable for Action {
2 => Action::UpdateLatency(Vec::<UpdateLatency>::read_from(buf)?), 2 => Action::UpdateLatency(Vec::<UpdateLatency>::read_from(buf)?),
3 => Action::UpdateDisplayName(Vec::<UpdateDisplayName>::read_from(buf)?), 3 => Action::UpdateDisplayName(Vec::<UpdateDisplayName>::read_from(buf)?),
4 => Action::RemovePlayer(Vec::<RemovePlayer>::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() }),
}) })
} }
} }

View file

@ -1,4 +1,4 @@
use azalea_buf::McBuf; use azalea_buf::{BufReadError, McBuf};
use azalea_buf::{McBufReadable, McBufWritable, Readable}; use azalea_buf::{McBufReadable, McBufWritable, Readable};
use packet_macros::ClientboundGamePacket; use packet_macros::ClientboundGamePacket;
use std::io::{Read, Write}; use std::io::{Read, Write};
@ -28,7 +28,7 @@ pub struct RelativeArguments {
} }
impl McBufReadable for 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()?; let byte = buf.read_byte()?;
Ok(RelativeArguments { Ok(RelativeArguments {
x: byte & 0b1 != 0, x: byte & 0b1 != 0,

View file

@ -1,4 +1,4 @@
use azalea_buf::McBuf; use azalea_buf::{BufReadError, McBuf};
use azalea_buf::{McBufReadable, McBufWritable, Readable, Writable}; use azalea_buf::{McBufReadable, McBufWritable, Readable, Writable};
use azalea_core::ResourceLocation; use azalea_core::ResourceLocation;
use packet_macros::ClientboundGamePacket; use packet_macros::ClientboundGamePacket;
@ -41,7 +41,7 @@ impl McBufWritable for State {
} }
} }
impl McBufReadable 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()?; let state = buf.read_varint()?;
Ok(match state { Ok(match state {
0 => State::Init, 0 => State::Init,

View file

@ -1,4 +1,4 @@
use azalea_buf::McBuf; use azalea_buf::{BufReadError, McBuf};
use azalea_buf::{McBufReadable, McBufVarReadable, McBufVarWritable, McBufWritable}; use azalea_buf::{McBufReadable, McBufVarReadable, McBufVarWritable, McBufWritable};
use azalea_core::{ChunkSectionBlockPos, ChunkSectionPos}; use azalea_core::{ChunkSectionBlockPos, ChunkSectionPos};
use packet_macros::ClientboundGamePacket; use packet_macros::ClientboundGamePacket;
@ -18,7 +18,7 @@ pub struct BlockStateWithPosition {
} }
impl McBufReadable for 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 data = u64::var_read_from(buf)?;
let position_part = data & 4095; let position_part = data & 4095;
let state = (data >> 12) as u32; let state = (data >> 12) as u32;

View file

@ -1,4 +1,4 @@
use azalea_buf::McBuf; use azalea_buf::{BufReadError, McBuf};
use azalea_core::Slot; use azalea_core::Slot;
use packet_macros::ClientboundGamePacket; use packet_macros::ClientboundGamePacket;
@ -17,13 +17,17 @@ pub struct EquipmentSlots {
} }
impl McBufReadable for 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![]; let mut slots = vec![];
loop { loop {
let equipment_byte = u8::read_from(buf)?; let equipment_byte = u8::read_from(buf)?;
let equipment_slot = EquipmentSlot::from_byte(equipment_byte & 127) let equipment_slot =
.ok_or_else(|| format!("Invalid equipment slot byte {}", equipment_byte))?; EquipmentSlot::from_byte(equipment_byte & 127).ok_or_else(|| {
BufReadError::UnexpectedEnumVariant {
id: equipment_byte.into(),
}
})?;
let item = Slot::read_from(buf)?; let item = Slot::read_from(buf)?;
slots.push((equipment_slot, item)); slots.push((equipment_slot, item));
if equipment_byte & 128 == 0 { if equipment_byte & 128 == 0 {

View file

@ -1,4 +1,4 @@
use azalea_buf::{McBuf, McBufReadable, McBufWritable}; use azalea_buf::{BufReadError, McBuf, McBufReadable, McBufWritable};
use azalea_chat::component::Component; use azalea_chat::component::Component;
use azalea_core::{ResourceLocation, Slot}; use azalea_core::{ResourceLocation, Slot};
use packet_macros::ClientboundGamePacket; use packet_macros::ClientboundGamePacket;
@ -45,7 +45,7 @@ pub struct DisplayFlags {
} }
impl McBufReadable for 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)?; let data = u32::read_from(buf)?;
Ok(DisplayFlags { Ok(DisplayFlags {
background: (data & 0b1) != 0, background: (data & 0b1) != 0,

View file

@ -1,4 +1,4 @@
use azalea_buf::McBuf; use azalea_buf::{BufReadError, McBuf};
use azalea_buf::{McBufReadable, McBufWritable, Readable, Writable}; use azalea_buf::{McBufReadable, McBufWritable, Readable, Writable};
use azalea_core::ResourceLocation; use azalea_core::ResourceLocation;
use packet_macros::ClientboundGamePacket; use packet_macros::ClientboundGamePacket;
@ -34,12 +34,12 @@ enum Operation {
} }
impl McBufReadable for 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()? { match buf.read_byte()? {
0 => Ok(Operation::Addition), 0 => Ok(Operation::Addition),
1 => Ok(Operation::MultiplyBase), 1 => Ok(Operation::MultiplyBase),
2 => Ok(Operation::MultiplyTotal), 2 => Ok(Operation::MultiplyTotal),
op => Err(format!("Unknown operation: {}", op)), id => Err(BufReadError::UnexpectedEnumVariant { id: id.into() }),
} }
} }
} }

View file

@ -1,6 +1,6 @@
use std::io::{Read, Write}; use std::io::{Read, Write};
use azalea_buf::McBuf; use azalea_buf::{BufReadError, McBuf};
use azalea_core::{ResourceLocation, Slot}; use azalea_core::{ResourceLocation, Slot};
use packet_macros::ClientboundGamePacket; use packet_macros::ClientboundGamePacket;
@ -49,7 +49,7 @@ impl McBufWritable for ShapedRecipe {
} }
} }
impl McBufReadable 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 width = buf.read_varint()?.try_into().unwrap();
let height = buf.read_varint()?.try_into().unwrap(); let height = buf.read_varint()?.try_into().unwrap();
let group = buf.read_utf()?; let group = buf.read_utf()?;
@ -129,7 +129,7 @@ impl McBufWritable for Recipe {
} }
impl McBufReadable 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 recipe_type = ResourceLocation::read_from(buf)?;
let identifier = ResourceLocation::read_from(buf)?; let identifier = ResourceLocation::read_from(buf)?;

View file

@ -1,4 +1,4 @@
use azalea_buf::McBuf; use azalea_buf::{BufReadError, McBuf};
use azalea_buf::{McBufReadable, McBufWritable, Readable, Writable}; use azalea_buf::{McBufReadable, McBufWritable, Readable, Writable};
use azalea_core::ResourceLocation; use azalea_core::ResourceLocation;
use packet_macros::ClientboundGamePacket; use packet_macros::ClientboundGamePacket;
@ -23,7 +23,7 @@ pub struct Tags {
pub struct TagMap(HashMap<ResourceLocation, Vec<Tags>>); pub struct TagMap(HashMap<ResourceLocation, Vec<Tags>>);
impl McBufReadable for TagMap { 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 length = buf.read_varint()? as usize;
let mut data = HashMap::with_capacity(length); let mut data = HashMap::with_capacity(length);
for _ in 0..length { for _ in 0..length {
@ -51,7 +51,7 @@ impl McBufWritable for TagMap {
} }
} }
impl McBufReadable for Tags { 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 name = ResourceLocation::read_from(buf)?;
let elements = buf.read_int_id_list()?; let elements = buf.read_int_id_list()?;
Ok(Tags { name, elements }) Ok(Tags { name, elements })

View file

@ -2,34 +2,11 @@ use std::io::{Read, Write};
use super::ClientboundLoginPacket; use super::ClientboundLoginPacket;
use azalea_auth::game_profile::GameProfile; 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; use uuid::Uuid;
#[derive(Clone, Debug)] #[derive(Clone, Debug, McBuf, ClientboundLoginPacket)]
pub struct ClientboundGameProfilePacket { pub struct ClientboundGameProfilePacket {
pub game_profile: GameProfile, 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())
}
}

View file

@ -3,7 +3,7 @@ use std::{
io::{Read, Write}, io::{Read, Write},
}; };
use azalea_buf::{Readable, Writable}; use azalea_buf::{BufReadError, Readable, Writable};
use super::ClientboundLoginPacket; use super::ClientboundLoginPacket;
@ -22,7 +22,7 @@ impl ClientboundLoginCompressionPacket {
Ok(()) 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()?; let compression_threshold = buf.read_varint()?;
Ok(ClientboundLoginCompressionPacket { Ok(ClientboundLoginCompressionPacket {

View file

@ -1,4 +1,4 @@
use azalea_buf::McBuf; use azalea_buf::{BufReadError, McBuf};
use azalea_crypto::SaltSignaturePair; use azalea_crypto::SaltSignaturePair;
use packet_macros::ServerboundLoginPacket; use packet_macros::ServerboundLoginPacket;
use std::io::{Read, Write}; use std::io::{Read, Write};
@ -18,7 +18,7 @@ pub enum NonceOrSaltSignature {
} }
impl McBufReadable for 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)?; let is_nonce = bool::read_from(buf)?;
if is_nonce { if is_nonce {
Ok(NonceOrSaltSignature::Nonce(Vec::<u8>::read_from(buf)?)) Ok(NonceOrSaltSignature::Nonce(Vec::<u8>::read_from(buf)?))

View file

@ -3,7 +3,8 @@ pub mod handshake;
pub mod login; pub mod login;
pub mod status; 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}; use std::io::{Read, Write};
pub const PROTOCOL_VERSION: u32 = 760; pub const PROTOCOL_VERSION: u32 = 760;
@ -36,15 +37,15 @@ where
fn id(&self) -> u32; fn id(&self) -> u32;
/// Read a packet by its id, ConnectionProtocol, and flow /// 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>; fn write(&self, buf: &mut impl Write) -> Result<(), std::io::Error>;
} }
impl azalea_buf::McBufReadable for ConnectionProtocol { impl azalea_buf::McBufReadable for ConnectionProtocol {
fn read_from(buf: &mut impl Read) -> Result<Self, String> { fn read_from(buf: &mut impl Read) -> Result<Self, BufReadError> {
ConnectionProtocol::from_i32(buf.read_varint()?) let id = buf.read_varint()?;
.ok_or_else(|| "Invalid intention".to_string()) ConnectionProtocol::from_i32(id).ok_or(BufReadError::UnexpectedEnumVariant { id })
} }
} }

View file

@ -1,5 +1,5 @@
use super::ClientboundStatusPacket; use super::ClientboundStatusPacket;
use azalea_buf::Readable; use azalea_buf::{BufReadError, Readable};
use azalea_chat::component::Component; use azalea_chat::component::Component;
use serde::Deserialize; use serde::Deserialize;
use serde_json::Value; use serde_json::Value;
@ -42,14 +42,11 @@ impl ClientboundStatusResponsePacket {
Ok(()) 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_string = buf.read_utf()?;
let status_json: Value = let status_json: Value = serde_json::from_str(status_string.as_str())?;
serde_json::from_str(status_string.as_str()).expect("Server status isn't valid JSON");
let packet = ClientboundStatusResponsePacket::deserialize(status_json) let packet = ClientboundStatusResponsePacket::deserialize(status_json)?.get();
.map_err(|e| e.to_string())?
.get();
Ok(packet) Ok(packet)
} }

View file

@ -1,5 +1,6 @@
use crate::packets::ProtocolPacket; 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 azalea_crypto::Aes128CfbDec;
use flate2::read::ZlibDecoder; use flate2::read::ZlibDecoder;
use std::{ use std::{
@ -8,32 +9,67 @@ use std::{
pin::Pin, pin::Pin,
task::{Context, Poll}, task::{Context, Poll},
}; };
use thiserror::Error;
use tokio::io::{AsyncRead, AsyncReadExt}; 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 where
R: AsyncRead + std::marker::Unpin + std::marker::Send, R: AsyncRead + std::marker::Unpin + std::marker::Send,
{ {
// Packet Length // Packet Length
let length_result = read_varint_async(&mut stream).await; let length = read_varint_async(&mut stream).await?;
match length_result {
Ok(length) => {
let mut buf = vec![0; length as usize];
stream let mut buf = vec![0; length as usize];
.read_exact(&mut buf) stream.read_exact(&mut buf).await?;
.await
.map_err(|e| e.to_string())?;
Ok(buf) Ok(buf)
}
Err(_) => Err("length wider than 21-bit".to_string()),
}
} }
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 // 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) P::read(packet_id.try_into().unwrap(), stream)
} }
@ -42,39 +78,57 @@ static VALIDATE_DECOMPRESSED: bool = true;
pub static MAXIMUM_UNCOMPRESSED_LENGTH: u32 = 2097152; 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( fn compression_decoder(
stream: &mut impl Read, stream: &mut impl Read,
compression_threshold: u32, compression_threshold: u32,
) -> Result<Vec<u8>, String> { ) -> Result<Vec<u8>, DecompressionError> {
// Data Length // Data Length
let n: u32 = stream.read_varint()?.try_into().unwrap(); let n = u32::var_read_from(stream)?;
if n == 0 { if n == 0 {
// no data size, no compression // no data size, no compression
let mut buf = vec![]; 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); return Ok(buf);
} }
if VALIDATE_DECOMPRESSED { if VALIDATE_DECOMPRESSED {
if n < compression_threshold { if n < compression_threshold {
return Err(format!( return Err(DecompressionError::BelowCompressionThreshold {
"Badly compressed packet - size of {} is below server threshold of {}", size: n,
n, compression_threshold threshold: compression_threshold,
)); });
} }
if n > MAXIMUM_UNCOMPRESSED_LENGTH { if n > MAXIMUM_UNCOMPRESSED_LENGTH {
return Err(format!( return Err(DecompressionError::AboveCompressionThreshold {
"Badly compressed packet - size of {} is larger than protocol maximum of {}", size: n,
n, MAXIMUM_UNCOMPRESSED_LENGTH maximum: MAXIMUM_UNCOMPRESSED_LENGTH,
)); });
} }
} }
let mut decoded_buf = vec![]; let mut decoded_buf = vec![];
let mut decoder = ZlibDecoder::new(stream); let mut decoder = ZlibDecoder::new(stream);
decoder decoder.read_to_end(&mut decoded_buf)?;
.read_to_end(&mut decoded_buf)
.map_err(|e| e.to_string())?;
Ok(decoded_buf) Ok(decoded_buf)
} }
@ -121,7 +175,7 @@ pub async fn read_packet<'a, P: ProtocolPacket, R>(
stream: &'a mut R, stream: &'a mut R,
compression_threshold: Option<u32>, compression_threshold: Option<u32>,
cipher: &mut Option<Aes128CfbDec>, cipher: &mut Option<Aes128CfbDec>,
) -> Result<P, String> ) -> Result<P, ReadPacketError>
where where
R: AsyncRead + std::marker::Unpin + std::marker::Send + std::marker::Sync, R: AsyncRead + std::marker::Unpin + std::marker::Send + std::marker::Sync,
{ {
@ -149,5 +203,7 @@ where
let packet = packet_decoder(&mut buf.as_slice())?; let packet = packet_decoder(&mut buf.as_slice())?;
// println!("decoded packet ({}ms)", start_time.elapsed().as_millis()); // println!("decoded packet ({}ms)", start_time.elapsed().as_millis());
if !buf.is_empty() {}
Ok(packet) Ok(packet)
} }

View file

@ -1,16 +1,24 @@
use std::net::IpAddr;
use crate::{ServerAddress, ServerIpAddress}; use crate::{ServerAddress, ServerIpAddress};
use async_recursion::async_recursion; use async_recursion::async_recursion;
use std::net::IpAddr;
use thiserror::Error;
use trust_dns_resolver::{ use trust_dns_resolver::{
config::{ResolverConfig, ResolverOpts}, config::{ResolverConfig, ResolverOpts},
TokioAsyncResolver, 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. /// Resolve a Minecraft server address into an IP address and port.
/// If it's already an IP address, it's returned as-is. /// If it's already an IP address, it's returned as-is.
#[async_recursion] #[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 the address.host is already in the format of an ip address, return it.
if let Ok(ip) = address.host.parse::<IpAddr>() { if let Ok(ip) = address.host.parse::<IpAddr>() {
return Ok(ServerIpAddress { return Ok(ServerIpAddress {
@ -33,20 +41,20 @@ pub async fn resolve_address(address: &ServerAddress) -> Result<ServerIpAddress,
let redirect_srv = redirect_result let redirect_srv = redirect_result
.iter() .iter()
.next() .next()
.ok_or_else(|| "No SRV record found".to_string())?; .ok_or(ResolverError::NoSrvRecord)?;
let redirect_address = ServerAddress { let redirect_address = ServerAddress {
host: redirect_srv.target().to_utf8(), host: redirect_srv.target().to_utf8(),
port: redirect_srv.port(), port: redirect_srv.port(),
}; };
println!("redirecting to {:?}", redirect_address); // println!("redirecting to {:?}", redirect_address);
return resolve_address(&redirect_address).await; return resolve_address(&redirect_address).await;
} }
// there's no redirect, try to resolve this as an ip address // 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_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 { Ok(ServerIpAddress {
ip: lookup_ip.iter().next().unwrap(), ip: lookup_ip.iter().next().unwrap(),

View file

@ -3,49 +3,67 @@ use async_compression::tokio::bufread::ZlibEncoder;
use azalea_buf::Writable; use azalea_buf::Writable;
use azalea_crypto::Aes128CfbEnc; use azalea_crypto::Aes128CfbEnc;
use std::fmt::Debug; use std::fmt::Debug;
use thiserror::Error;
use tokio::io::{AsyncReadExt, AsyncWrite, AsyncWriteExt}; 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(); let mut buf = Vec::new();
buf.write_varint(data.len() as i32) buf.write_varint(data.len() as i32)?;
.map_err(|e| e.to_string())?;
buf.append(data); buf.append(data);
Ok(buf) 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(); let mut buf = Vec::new();
buf.write_varint(packet.id() as i32) buf.write_varint(packet.id() as i32)?;
.map_err(|e| e.to_string())?; packet.write(&mut buf)?;
packet.write(&mut buf).map_err(|e| e.to_string())?;
if buf.len() > MAXIMUM_UNCOMPRESSED_LENGTH as usize { if buf.len() > MAXIMUM_UNCOMPRESSED_LENGTH as usize {
return Err(format!( return Err(PacketEncodeError::TooBig {
"Packet too big (is {} bytes, should be less than {}): {:?}", actual: buf.len(),
buf.len(), maximum: MAXIMUM_UNCOMPRESSED_LENGTH as usize,
MAXIMUM_UNCOMPRESSED_LENGTH, packet_string: format!("{:?}", packet),
packet });
));
} }
Ok(buf) 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(); let n = data.len();
// if it's less than the compression threshold, don't compress // if it's less than the compression threshold, don't compress
if n < compression_threshold as usize { if n < compression_threshold as usize {
let mut buf = Vec::new(); let mut buf = Vec::new();
buf.write_varint(0).map_err(|e| e.to_string())?; buf.write_varint(0)?;
buf.write_all(data).await.map_err(|e| e.to_string())?; buf.write_all(data).await?;
Ok(buf) Ok(buf)
} else { } else {
// otherwise, compress // otherwise, compress
let mut deflater = ZlibEncoder::new(data); let mut deflater = ZlibEncoder::new(data);
// write deflated data to buf // write deflated data to buf
let mut buf = Vec::new(); let mut buf = Vec::new();
deflater deflater.read_to_end(&mut buf).await?;
.read_to_end(&mut buf)
.await
.map_err(|e| e.to_string())?;
Ok(buf) Ok(buf)
} }
} }
@ -55,7 +73,8 @@ pub async fn write_packet<P, W>(
stream: &mut W, stream: &mut W,
compression_threshold: Option<u32>, compression_threshold: Option<u32>,
cipher: &mut Option<Aes128CfbEnc>, cipher: &mut Option<Aes128CfbEnc>,
) where ) -> std::io::Result<()>
where
P: ProtocolPacket + Debug, P: ProtocolPacket + Debug,
W: AsyncWrite + Unpin + Send, W: AsyncWrite + Unpin + Send,
{ {
@ -68,5 +87,5 @@ pub async fn write_packet<P, W>(
if let Some(cipher) = cipher { if let Some(cipher) = cipher {
azalea_crypto::encrypt_packet(cipher, &mut buf); azalea_crypto::encrypt_packet(cipher, &mut buf);
} }
stream.write_all(&buf).await.unwrap(); stream.write_all(&buf).await
} }

View file

@ -13,6 +13,7 @@ azalea-entity = {path = "../azalea-entity"}
azalea-nbt = {path = "../azalea-nbt"} azalea-nbt = {path = "../azalea-nbt"}
log = "0.4.17" log = "0.4.17"
nohash-hasher = "0.2.0" nohash-hasher = "0.2.0"
thiserror = "1.0.32"
uuid = "1.1.2" uuid = "1.1.2"
[profile.release] [profile.release]

View file

@ -2,6 +2,7 @@ use crate::palette::PalettedContainer;
use crate::palette::PalettedContainerType; use crate::palette::PalettedContainerType;
use crate::Dimension; use crate::Dimension;
use azalea_block::BlockState; use azalea_block::BlockState;
use azalea_buf::BufReadError;
use azalea_buf::{McBufReadable, McBufWritable}; use azalea_buf::{McBufReadable, McBufWritable};
use azalea_core::{BlockPos, ChunkBlockPos, ChunkPos, ChunkSectionBlockPos}; use azalea_core::{BlockPos, ChunkBlockPos, ChunkPos, ChunkSectionBlockPos};
use std::fmt::Debug; use std::fmt::Debug;
@ -69,7 +70,7 @@ impl ChunkStorage {
&mut self, &mut self,
pos: &ChunkPos, pos: &ChunkPos,
data: &mut impl Read, data: &mut impl Read,
) -> Result<(), String> { ) -> Result<(), BufReadError> {
if !self.in_range(pos) { if !self.in_range(pos) {
println!( println!(
"Ignoring chunk since it's not in the view range: {}, {}", "Ignoring chunk since it's not in the view range: {}, {}",
@ -109,14 +110,17 @@ pub struct Chunk {
} }
impl 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()) Self::read_with_dimension_height(buf, data.height())
} }
pub fn read_with_dimension_height( pub fn read_with_dimension_height(
buf: &mut impl Read, buf: &mut impl Read,
dimension_height: u32, dimension_height: u32,
) -> Result<Self, String> { ) -> Result<Self, BufReadError> {
let section_count = dimension_height / SECTION_HEIGHT; let section_count = dimension_height / SECTION_HEIGHT;
let mut sections = Vec::with_capacity(section_count as usize); let mut sections = Vec::with_capacity(section_count as usize);
for _ in 0..section_count { for _ in 0..section_count {
@ -174,7 +178,7 @@ pub struct Section {
} }
impl McBufReadable for 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)?; let block_count = u16::read_from(buf)?;
// this is commented out because the vanilla server is wrong // 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() { for i in 0..states.storage.size() {
if !BlockState::is_valid_state(states.storage.get(i) as u32) { 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.", "Invalid block state {} (index {}) found in section.",
states.storage.get(i), states.storage.get(i),
i i
)); )));
} }
} }

View file

@ -6,6 +6,7 @@ mod entity;
mod palette; mod palette;
use azalea_block::BlockState; use azalea_block::BlockState;
use azalea_buf::BufReadError;
use azalea_core::{BlockPos, ChunkPos, EntityPos, PositionDelta8}; use azalea_core::{BlockPos, ChunkPos, EntityPos, PositionDelta8};
use azalea_entity::Entity; use azalea_entity::Entity;
pub use bit_storage::BitStorage; pub use bit_storage::BitStorage;
@ -16,6 +17,7 @@ use std::{
ops::{Index, IndexMut}, ops::{Index, IndexMut},
sync::{Arc, Mutex}, sync::{Arc, Mutex},
}; };
use thiserror::Error;
use uuid::Uuid; use uuid::Uuid;
#[cfg(test)] #[cfg(test)]
@ -34,6 +36,12 @@ pub struct Dimension {
entity_storage: EntityStorage, entity_storage: EntityStorage,
} }
#[derive(Error, Debug)]
pub enum MoveEntityError {
#[error("Entity doesn't exist")]
EntityDoesNotExist,
}
impl Dimension { impl Dimension {
pub fn new(chunk_radius: u32, height: u32, min_y: i32) -> Self { pub fn new(chunk_radius: u32, height: u32, min_y: i32) -> Self {
Dimension { Dimension {
@ -46,7 +54,7 @@ impl Dimension {
&mut self, &mut self,
pos: &ChunkPos, pos: &ChunkPos,
data: &mut impl Read, data: &mut impl Read,
) -> Result<(), String> { ) -> Result<(), BufReadError> {
self.chunk_storage.replace_with_packet_data(pos, data) 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()) 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 let entity = self
.entity_storage .entity_storage
.get_mut_by_id(entity_id) .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 old_chunk = ChunkPos::from(entity.pos());
let new_chunk = ChunkPos::from(&new_pos); let new_chunk = ChunkPos::from(&new_pos);
@ -79,11 +91,11 @@ impl Dimension {
&mut self, &mut self,
entity_id: u32, entity_id: u32,
delta: &PositionDelta8, delta: &PositionDelta8,
) -> Result<(), String> { ) -> Result<(), MoveEntityError> {
let entity = self let entity = self
.entity_storage .entity_storage
.get_mut_by_id(entity_id) .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 new_pos = entity.pos().with_delta(delta);
let old_chunk = ChunkPos::from(entity.pos()); let old_chunk = ChunkPos::from(entity.pos());

View file

@ -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 std::io::{Read, Write};
use crate::BitStorage; use crate::BitStorage;
@ -22,7 +24,7 @@ impl PalettedContainer {
pub fn read_with_type( pub fn read_with_type(
buf: &mut impl Read, buf: &mut impl Read,
type_: &'static PalettedContainerType, type_: &'static PalettedContainerType,
) -> Result<Self, String> { ) -> Result<Self, BufReadError> {
let bits_per_entry = buf.read_byte()?; let bits_per_entry = buf.read_byte()?;
let palette = match type_ { let palette = match type_ {
PalettedContainerType::BlockStates => { PalettedContainerType::BlockStates => {
@ -90,7 +92,7 @@ impl Palette {
pub fn block_states_read_with_bits_per_entry( pub fn block_states_read_with_bits_per_entry(
buf: &mut impl Read, buf: &mut impl Read,
bits_per_entry: u8, bits_per_entry: u8,
) -> Result<Palette, String> { ) -> Result<Palette, BufReadError> {
Ok(match bits_per_entry { Ok(match bits_per_entry {
0 => Palette::SingleValue(u32::var_read_from(buf)?), 0 => Palette::SingleValue(u32::var_read_from(buf)?),
1..=4 => Palette::Linear(Vec::<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( pub fn biomes_read_with_bits_per_entry(
buf: &mut impl Read, buf: &mut impl Read,
bits_per_entry: u8, bits_per_entry: u8,
) -> Result<Palette, String> { ) -> Result<Palette, BufReadError> {
Ok(match bits_per_entry { Ok(match bits_per_entry {
0 => Palette::SingleValue(u32::var_read_from(buf)?), 0 => Palette::SingleValue(u32::var_read_from(buf)?),
1..=3 => Palette::Linear(Vec::<u32>::var_read_from(buf)?), 1..=3 => Palette::Linear(Vec::<u32>::var_read_from(buf)?),