Skip to main content

azalea_buf/impls/
mod.rs

1#![allow(clippy::redundant_field_names, reason = "Triggered by `Error` derive")]
2
3mod extra;
4pub mod primitives;
5
6use std::{
7    backtrace::Backtrace,
8    io::{self, Cursor, Write},
9};
10
11use thiserror::Error;
12use tracing::warn;
13
14use crate::Ctx;
15
16/// A trait that's implemented on types that are used by the Minecraft protocol.
17pub trait AzBuf
18where
19    Self: Sized,
20{
21    fn azalea_read(ctx: Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError>;
22    fn azalea_write(&self, ctx: crate::Ctx, buf: &mut impl Write) -> io::Result<()>;
23}
24
25/// Used for types that have an alternative variable-length encoding.
26///
27/// This mostly exists for varints.
28pub trait AzBufVar
29where
30    Self: Sized,
31{
32    fn azalea_read_var(ctx: crate::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError>;
33    fn azalea_write_var(&self, ctx: crate::Ctx, buf: &mut impl Write) -> io::Result<()>;
34}
35
36/// Used for types that have some configurable limit.
37///
38/// For example, the implementation of this on `String` limits the maximum
39/// length of the string.
40///
41/// This exists partially as an anti-abuse mechanism in Minecraft, so there is
42/// no limited write function.
43pub trait AzBufLimited
44where
45    Self: Sized,
46{
47    fn azalea_read_limited(
48        ctx: crate::Ctx,
49        buf: &mut Cursor<&[u8]>,
50        limit: u32,
51    ) -> Result<Self, BufReadError>;
52}
53
54#[derive(Debug, Error)]
55pub enum BufReadErrorRepr {
56    #[error("Invalid VarInt")]
57    InvalidVarInt,
58    #[error("Invalid VarLong")]
59    InvalidVarLong,
60    #[error("Error reading bytes")]
61    CouldNotReadBytes,
62    #[error(
63        "The received encoded string buffer length is longer than maximum allowed ({length} > {max_length})"
64    )]
65    StringLengthTooLong { length: u32, max_length: u32 },
66    #[error("The received Vec length is longer than maximum allowed ({length} > {max_length})")]
67    VecLengthTooLong { length: u32, max_length: u32 },
68    #[error("{source}")]
69    Io {
70        #[from]
71        source: io::Error,
72    },
73    #[error("Invalid UTF-8: {bytes:?} (lossy: {:?})", String::from_utf8_lossy(bytes).to_string())]
74    InvalidUtf8 { bytes: Box<[u8]> },
75    #[error("Unexpected enum variant {id}")]
76    UnexpectedEnumVariant { id: i32 },
77    #[error("Unexpected enum variant {id}")]
78    UnexpectedStringEnumVariant { id: Box<str> },
79    #[error("Tried to read {attempted_read} bytes but there were only {actual_read}")]
80    UnexpectedEof {
81        attempted_read: usize,
82        actual_read: usize,
83    },
84    #[error("The recursion depth limit was exceeded")]
85    DepthLimitExceeded,
86    #[error("{0}")]
87    Custom(Box<str>),
88    #[cfg(feature = "serde_json")]
89    #[error("{source}")]
90    SerdeJson {
91        #[from]
92        source: serde_json::Error,
93    },
94    #[cfg(feature = "simd-json")]
95    #[error("{source}")]
96    SimdJson {
97        #[from]
98        source: Box<simd_json::Error>,
99    },
100    #[error("{source}")]
101    Nbt {
102        #[from]
103        source: simdnbt::Error,
104    },
105    #[error("{source}")]
106    Codec {
107        #[from]
108        source: Box<azalea_codec::error::ReadError>,
109    },
110}
111
112// the only reason this is separated into a different type is for the backtrace
113// impl
114#[derive(Debug)]
115pub struct BufReadErrorInner {
116    pub repr: BufReadErrorRepr,
117    pub backtrace: Backtrace,
118}
119#[derive(Debug, Error)]
120#[error("{}", self.0.repr)]
121pub struct BufReadError(pub Box<BufReadErrorInner>);
122
123impl From<BufReadErrorRepr> for BufReadError {
124    fn from(repr: BufReadErrorRepr) -> Self {
125        Self(Box::new(BufReadErrorInner {
126            repr,
127            backtrace: Backtrace::capture(),
128        }))
129    }
130}
131
132impl BufReadError {
133    // maybe we should add more of these in the future
134    pub fn custom(message: impl Into<Box<str>>) -> Self {
135        // ^ this is intentionally Into<Box<str>> rather than ToString to avoid
136        // being too permissive
137        Self::from(BufReadErrorRepr::Custom(message.into()))
138    }
139}
140macro_rules! buf_read_error_from_impl {
141    ($ty: ty $(,$function:path)?) => {
142        impl From<$ty> for BufReadError {
143            fn from(e: $ty) -> Self {
144                Self::from(BufReadErrorRepr::from($($function)?(e)))
145            }
146        }
147    };
148}
149buf_read_error_from_impl!(io::Error);
150buf_read_error_from_impl!(simdnbt::Error);
151buf_read_error_from_impl!(azalea_codec::error::ReadError, Box::new);
152#[cfg(feature = "serde_json")]
153buf_read_error_from_impl!(serde_json::Error);
154#[cfg(feature = "simd-json")]
155buf_read_error_from_impl!(simd_json::Error, Box::new);
156
157pub(crate) fn read_bytes<'a>(
158    buf: &'a mut Cursor<&[u8]>,
159    length: usize,
160) -> Result<&'a [u8], BufReadError> {
161    let max_length = buf.get_ref().len() - buf.position() as usize;
162    if length > max_length {
163        warn!("requested buf length {length} exceeds max length {max_length}");
164        return Err(BufReadErrorRepr::UnexpectedEof {
165            attempted_read: length,
166            actual_read: max_length,
167        }
168        .into());
169    }
170    let initial_position = buf.position() as usize;
171    buf.set_position(buf.position() + length as u64);
172    let data = &buf.get_ref()[initial_position..initial_position + length];
173    Ok(data)
174}
175
176pub(crate) fn read_utf8_with_len<'a>(
177    ctx: crate::Ctx,
178    buf: &'a mut Cursor<&[u8]>,
179    max_length: u32,
180) -> Result<&'a str, BufReadError> {
181    let length = u32::azalea_read_var(ctx, buf)?;
182    // multiply the max by 4 because this length is for unicode codepoints
183    if length > max_length * 4 {
184        warn!("string length {length} exceeds max length {max_length}");
185        return Err(BufReadErrorRepr::StringLengthTooLong {
186            length,
187            max_length: max_length * 4,
188        }
189        .into());
190    }
191
192    let buffer = read_bytes(buf, length as usize)?;
193    let string = std::str::from_utf8(buffer).map_err(|_| BufReadErrorRepr::InvalidUtf8 {
194        bytes: buffer.into(),
195    })?;
196    if string.len() > length as usize {
197        return Err(BufReadErrorRepr::StringLengthTooLong { length, max_length }.into());
198    }
199
200    Ok(string)
201}
202
203pub(crate) fn write_utf_with_len(
204    ctx: crate::Ctx,
205    buf: &mut impl Write,
206    string: &str,
207    max_len: u32,
208) -> io::Result<()> {
209    let actual_len = string.len();
210    if actual_len > max_len as usize {
211        panic!("String too big (was {actual_len} bytes encoded, max {max_len})");
212    }
213    string.as_bytes().to_vec().azalea_write(ctx, buf)?;
214    Ok(())
215}