azalea_buf/
read.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
use std::{
    backtrace::Backtrace,
    collections::HashMap,
    hash::Hash,
    io::{Cursor, Read},
};

use byteorder::{ReadBytesExt, BE};
use thiserror::Error;
use tracing::warn;

use super::{UnsizedByteArray, MAX_STRING_LENGTH};

#[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 longer than maximum allowed ({length} > {max_length})")]
    StringLengthTooLong { length: u32, max_length: u32 },
    #[error("{source}")]
    Io {
        #[from]
        #[backtrace]
        source: std::io::Error,
    },
    #[error("Invalid UTF-8: {bytes:?} (lossy: {lossy:?})")]
    InvalidUtf8 {
        bytes: Vec<u8>,
        lossy: String,
        // backtrace: Backtrace,
    },
    #[error("Unexpected enum variant {id}")]
    UnexpectedEnumVariant { id: i32 },
    #[error("Unexpected enum variant {id}")]
    UnexpectedStringEnumVariant { id: String },
    #[error("Tried to read {attempted_read} bytes but there were only {actual_read}")]
    UnexpectedEof {
        attempted_read: usize,
        actual_read: usize,
        backtrace: Backtrace,
    },
    #[error("{0}")]
    Custom(String),
    #[cfg(feature = "serde_json")]
    #[error("{source}")]
    Deserialization {
        #[from]
        #[backtrace]
        source: serde_json::Error,
    },
    #[error("{source}")]
    Nbt {
        #[from]
        #[backtrace]
        source: simdnbt::Error,
    },
    #[error("{source}")]
    DeserializeNbt {
        #[from]
        #[backtrace]
        source: simdnbt::DeserializeError,
    },
}

fn read_bytes<'a>(buf: &'a mut Cursor<&[u8]>, length: usize) -> Result<&'a [u8], BufReadError> {
    if length > (buf.get_ref().len() - buf.position() as usize) {
        return Err(BufReadError::UnexpectedEof {
            attempted_read: length,
            actual_read: buf.get_ref().len() - buf.position() as usize,
            backtrace: Backtrace::capture(),
        });
    }
    let initial_position = buf.position() as usize;
    buf.set_position(buf.position() + length as u64);
    let data = &buf.get_ref()[initial_position..initial_position + length];
    Ok(data)
}

fn read_utf_with_len(buf: &mut Cursor<&[u8]>, max_length: u32) -> Result<String, BufReadError> {
    let length = u32::var_read_from(buf)?;
    // i don't know why it's multiplied by 4 but it's like that in mojang's code so
    if length > max_length * 4 {
        return Err(BufReadError::StringLengthTooLong {
            length,
            max_length: max_length * 4,
        });
    }

    let buffer = read_bytes(buf, length as usize)?;
    let string = std::str::from_utf8(buffer)
        .map_err(|_| BufReadError::InvalidUtf8 {
            bytes: buffer.to_vec(),
            lossy: String::from_utf8_lossy(buffer).to_string(),
            // backtrace: Backtrace::capture(),
        })?
        .to_string();
    if string.len() > length as usize {
        return Err(BufReadError::StringLengthTooLong { length, max_length });
    }

    Ok(string)
}

pub trait McBufReadable
where
    Self: Sized,
{
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError>;
}

pub trait McBufVarReadable
where
    Self: Sized,
{
    fn var_read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError>;
}

impl McBufReadable for i32 {
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        Ok(buf.read_i32::<BE>()?)
    }
}

impl McBufVarReadable for i32 {
    // 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
    fn var_read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        let mut buffer = [0];
        let mut ans = 0;
        for i in 0..5 {
            buf.read_exact(&mut buffer)?;
            ans |= ((buffer[0] & 0b0111_1111) as i32) << (7 * i);
            if buffer[0] & 0b1000_0000 == 0 {
                break;
            }
        }
        Ok(ans)
    }
}

impl McBufVarReadable for i64 {
    // fast varints modified from https://github.com/luojia65/mc-varint/blob/master/src/lib.rs#L54
    fn var_read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        let mut buffer = [0];
        let mut ans = 0;
        for i in 0..10 {
            buf.read_exact(&mut buffer)
                .map_err(|_| BufReadError::InvalidVarLong)?;
            ans |= ((buffer[0] & 0b0111_1111) as i64) << (7 * i);
            if buffer[0] & 0b1000_0000 == 0 {
                break;
            }
        }
        Ok(ans)
    }
}
impl McBufVarReadable for u64 {
    fn var_read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        i64::var_read_from(buf).map(|i| i as u64)
    }
}

impl McBufReadable for UnsizedByteArray {
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        // read to end of the buffer
        let data = buf.get_ref()[buf.position() as usize..].to_vec();
        buf.set_position((buf.position()) + data.len() as u64);
        Ok(UnsizedByteArray(data))
    }
}

impl<T: McBufReadable + Send> McBufReadable for Vec<T> {
    default fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        let length = u32::var_read_from(buf)? as usize;
        // we limit the capacity to not get exploited into allocating a bunch
        let mut contents = Vec::with_capacity(usize::min(length, 65536));
        for _ in 0..length {
            contents.push(T::read_from(buf)?);
        }
        Ok(contents)
    }
}

impl<K: McBufReadable + Send + Eq + Hash, V: McBufReadable + Send> McBufReadable for HashMap<K, V> {
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        let length = i32::var_read_from(buf)? as usize;
        let mut contents = HashMap::with_capacity(usize::min(length, 65536));
        for _ in 0..length {
            contents.insert(K::read_from(buf)?, V::read_from(buf)?);
        }
        Ok(contents)
    }
}

impl<K: McBufReadable + Send + Eq + Hash, V: McBufVarReadable + Send> McBufVarReadable
    for HashMap<K, V>
{
    fn var_read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        let length = i32::var_read_from(buf)? as usize;
        let mut contents = HashMap::with_capacity(usize::min(length, 65536));
        for _ in 0..length {
            contents.insert(K::read_from(buf)?, V::var_read_from(buf)?);
        }
        Ok(contents)
    }
}

impl McBufReadable for Vec<u8> {
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        let length = i32::var_read_from(buf)? as usize;
        read_bytes(buf, length).map(|b| b.to_vec())
    }
}

impl McBufReadable for String {
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        read_utf_with_len(buf, MAX_STRING_LENGTH.into())
    }
}

impl McBufReadable for u32 {
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        Ok(i32::read_from(buf)? as u32)
    }
}

impl McBufVarReadable for u32 {
    fn var_read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        Ok(i32::var_read_from(buf)? as u32)
    }
}

impl McBufReadable for u16 {
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        i16::read_from(buf).map(|i| i as u16)
    }
}

impl McBufReadable for i16 {
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        Ok(buf.read_i16::<BE>()?)
    }
}

impl McBufVarReadable for u16 {
    fn var_read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        Ok(i32::var_read_from(buf)? as u16)
    }
}

impl<T: McBufVarReadable> McBufVarReadable for Vec<T> {
    fn var_read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        let length = i32::var_read_from(buf)? as usize;
        let mut contents = Vec::with_capacity(usize::min(length, 65536));
        for _ in 0..length {
            contents.push(T::var_read_from(buf)?);
        }
        Ok(contents)
    }
}

impl McBufReadable for i64 {
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        Ok(buf.read_i64::<BE>()?)
    }
}

impl McBufReadable for u64 {
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        i64::read_from(buf).map(|i| i as u64)
    }
}

impl McBufReadable for bool {
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        let byte = u8::read_from(buf)?;
        if byte > 1 {
            warn!("Boolean value was not 0 or 1, but {}", byte);
        }
        Ok(byte != 0)
    }
}

impl McBufReadable for u8 {
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        Ok(buf.read_u8()?)
    }
}

impl McBufReadable for i8 {
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        u8::read_from(buf).map(|i| i as i8)
    }
}

impl McBufReadable for f32 {
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        Ok(buf.read_f32::<BE>()?)
    }
}

impl McBufReadable for f64 {
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        Ok(buf.read_f64::<BE>()?)
    }
}

impl<T: McBufReadable> McBufReadable for Option<T> {
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        let present = bool::read_from(buf)?;
        Ok(if present {
            Some(T::read_from(buf)?)
        } else {
            None
        })
    }
}

impl<T: McBufVarReadable> McBufVarReadable for Option<T> {
    fn var_read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        let present = bool::read_from(buf)?;
        Ok(if present {
            Some(T::var_read_from(buf)?)
        } else {
            None
        })
    }
}

// [String; 4]
impl<T: McBufReadable, const N: usize> McBufReadable for [T; N] {
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        let mut contents = Vec::with_capacity(N);
        for _ in 0..N {
            contents.push(T::read_from(buf)?);
        }
        contents.try_into().map_err(|_| {
            unreachable!("Panic is not possible since the Vec is the same size as the array")
        })
    }
}

impl McBufReadable for simdnbt::owned::NbtTag {
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        Ok(simdnbt::owned::read_tag(buf).map_err(simdnbt::Error::from)?)
    }
}

impl McBufReadable for simdnbt::owned::NbtCompound {
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        match simdnbt::owned::read_tag(buf).map_err(simdnbt::Error::from)? {
            simdnbt::owned::NbtTag::Compound(compound) => Ok(compound),
            _ => Err(BufReadError::Custom("Expected compound tag".to_string())),
        }
    }
}

impl McBufReadable for simdnbt::owned::Nbt {
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        Ok(simdnbt::owned::read_unnamed(buf)?)
    }
}

impl<T> McBufReadable for Box<T>
where
    T: McBufReadable,
{
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        Ok(Box::new(T::read_from(buf)?))
    }
}