1#![allow(clippy::redundant_field_names, reason = "Triggered by `Error` derive")]
3
4use std::{
5 env,
6 fmt::Debug,
7 io,
8 io::{Cursor, Read},
9 sync::LazyLock,
10};
11
12use azalea_buf::{AzBufVar, BufReadError, BufReadErrorRepr};
13use azalea_crypto::Aes128CfbDec;
14use flate2::read::ZlibDecoder;
15use futures::StreamExt;
16use futures_lite::future;
17use thiserror::Error;
18use tokio::io::AsyncRead;
19use tokio_util::{
20 bytes::Buf,
21 codec::{BytesCodec, FramedRead},
22};
23use tracing::trace;
24
25use crate::packets::ProtocolPacket;
26
27#[derive(Debug, Error)]
28pub enum ReadPacketError {
29 #[error("Error reading packet {packet_name} (id {packet_id}): {source}")]
30 Parse {
31 packet_id: u32,
32 packet_name: String,
33 #[backtrace]
34 source: BufReadError,
35 },
36 #[error("Unknown packet id {id} in state {state_name}")]
37 UnknownPacketId { state_name: String, id: u32 },
38 #[error("Couldn't read packet id")]
39 ReadPacketId { source: BufReadError },
40 #[error(transparent)]
41 Decompress {
42 #[from]
43 #[backtrace]
44 source: DecompressionError,
45 },
46 #[error(transparent)]
47 FrameSplitter {
48 #[from]
49 #[backtrace]
50 source: FrameSplitterError,
51 },
52 #[error("Leftover data after reading packet {packet_name}: {data:?}")]
53 LeftoverData { data: Vec<u8>, packet_name: String },
54 #[error(transparent)]
55 IoError {
56 #[from]
57 #[backtrace]
58 source: io::Error,
59 },
60 #[error("Connection closed")]
61 ConnectionClosed,
62}
63
64#[derive(Debug, Error)]
65pub enum FrameSplitterError {
66 #[error("Couldn't read VarInt length for packet. The previous packet may have been corrupted")]
67 LengthRead {
68 #[from]
69 source: BufReadError,
70 },
71 #[error("Io error")]
72 Io {
73 #[from]
74 #[backtrace]
75 source: io::Error,
76 },
77 #[error("Packet is longer than {max} bytes (is {size})")]
78 BadLength { max: usize, size: usize },
79 #[error("Connection reset by peer")]
80 ConnectionReset,
81 #[error("Connection closed")]
82 ConnectionClosed,
83}
84
85fn parse_frame(buffer: &mut Cursor<Vec<u8>>) -> Result<Box<[u8]>, FrameSplitterError> {
89 let mut buffer_copy = Cursor::new(&buffer.get_ref()[buffer.position() as usize..]);
92
93 let ctx = azalea_buf::Ctx::default();
94
95 let length = match u32::azalea_read_var(ctx, &mut buffer_copy) {
96 Ok(length) => length as usize,
97 Err(err) => match err.0.repr {
98 BufReadErrorRepr::Io { source } => return Err(FrameSplitterError::Io { source }),
99 _ => return Err(err.into()),
100 },
101 };
102
103 if length > buffer_copy.remaining() {
104 return Err(FrameSplitterError::BadLength {
105 max: buffer_copy.remaining(),
106 size: length,
107 });
108 }
109
110 let varint_length = buffer.remaining() - buffer_copy.remaining();
115
116 buffer.advance(varint_length);
117 let data =
118 buffer.get_ref()[buffer.position() as usize..buffer.position() as usize + length].to_vec();
119 buffer.advance(length);
120
121 if buffer.position() == buffer.get_ref().len() as u64 {
122 buffer.get_mut().clear();
125
126 buffer.get_mut().shrink_to(1024 * 64);
131
132 buffer.set_position(0);
133 }
134
135 Ok(data.into_boxed_slice())
136}
137
138fn frame_splitter(buffer: &mut Cursor<Vec<u8>>) -> Result<Option<Box<[u8]>>, FrameSplitterError> {
139 let read_frame = parse_frame(buffer);
141 match read_frame {
142 Ok(frame) => return Ok(Some(frame)),
143 Err(err) => match err {
144 FrameSplitterError::BadLength { .. } | FrameSplitterError::Io { .. } => {
145 }
147 _ => return Err(err),
148 },
149 }
150
151 Ok(None)
152}
153
154pub fn deserialize_packet<P: ProtocolPacket + Debug>(
155 ctx: azalea_buf::Ctx<'_>,
156 stream: &mut Cursor<&[u8]>,
157) -> Result<P, Box<ReadPacketError>> {
158 let packet_id = u32::azalea_read_var(ctx, stream)
159 .map_err(|e| ReadPacketError::ReadPacketId { source: e })?;
160 P::read(packet_id, ctx, stream)
161}
162
163static VALIDATE_DECOMPRESSED: bool = true;
165
166pub static MAXIMUM_UNCOMPRESSED_LENGTH: u32 = 8_388_608;
167
168#[derive(Debug, Error)]
169pub enum DecompressionError {
170 #[error("Couldn't read VarInt length for data")]
171 LengthReadError {
172 #[from]
173 source: BufReadError,
174 },
175 #[error("Io error")]
176 Io {
177 #[from]
178 #[backtrace]
179 source: io::Error,
180 },
181 #[error("Badly compressed packet - size of {size} is below server threshold of {threshold}")]
182 BelowCompressionThreshold { size: u32, threshold: u32 },
183 #[error(
184 "Badly compressed packet - size of {size} is larger than protocol maximum of {maximum}"
185 )]
186 AboveCompressionThreshold { size: u32, maximum: u32 },
187}
188
189pub fn compression_decoder(
194 stream: &mut Cursor<&[u8]>,
195 compression_threshold: u32,
196) -> Result<Box<[u8]>, DecompressionError> {
197 let ctx = azalea_buf::Ctx::default();
198
199 let data_length = u32::azalea_read_var(ctx, stream)?;
200 if data_length == 0 {
201 let buf = stream.get_ref()[stream.position() as usize..]
203 .to_vec()
204 .into_boxed_slice();
205 stream.set_position(stream.get_ref().len() as u64);
206 return Ok(buf);
207 }
208
209 if VALIDATE_DECOMPRESSED {
210 if data_length < compression_threshold {
211 return Err(DecompressionError::BelowCompressionThreshold {
212 size: data_length,
213 threshold: compression_threshold,
214 });
215 }
216 if data_length > MAXIMUM_UNCOMPRESSED_LENGTH {
217 return Err(DecompressionError::AboveCompressionThreshold {
218 size: data_length,
219 maximum: MAXIMUM_UNCOMPRESSED_LENGTH,
220 });
221 }
222 }
223
224 let mut decoded_buf = vec![0; data_length as usize];
227
228 let mut decoder = ZlibDecoder::new(stream);
229 decoder.read_exact(&mut decoded_buf)?;
230
231 Ok(decoded_buf.into_boxed_slice())
232}
233
234pub async fn read_packet<P: ProtocolPacket + Debug, R>(
243 ctx: azalea_buf::Ctx<'_>,
244 stream: &mut R,
245 buffer: &mut Cursor<Vec<u8>>,
246 compression_threshold: Option<u32>,
247 cipher: &mut Option<Aes128CfbDec>,
248) -> Result<P, Box<ReadPacketError>>
249where
250 R: AsyncRead + Unpin + Send + Sync,
251{
252 let raw_packet = read_raw_packet(stream, buffer, compression_threshold, cipher).await?;
253 let packet = deserialize_packet(ctx, &mut Cursor::new(&raw_packet))?;
254 Ok(packet)
255}
256
257pub fn try_read_packet<P: ProtocolPacket + Debug, R>(
260 ctx: azalea_buf::Ctx<'_>,
261 stream: &mut R,
262 buffer: &mut Cursor<Vec<u8>>,
263 compression_threshold: Option<u32>,
264 cipher: &mut Option<Aes128CfbDec>,
265) -> Result<Option<P>, Box<ReadPacketError>>
266where
267 R: AsyncRead + Unpin + Send + Sync,
268{
269 let Some(raw_packet) = try_read_raw_packet(stream, buffer, compression_threshold, cipher)?
270 else {
271 return Ok(None);
272 };
273 let packet = deserialize_packet(ctx, &mut Cursor::new(&raw_packet))?;
274 Ok(Some(packet))
275}
276
277pub async fn read_raw_packet<R>(
278 stream: &mut R,
279 buffer: &mut Cursor<Vec<u8>>,
280 compression_threshold: Option<u32>,
281 cipher: &mut Option<Aes128CfbDec>,
284) -> Result<Box<[u8]>, Box<ReadPacketError>>
285where
286 R: AsyncRead + Unpin + Send + Sync,
287{
288 loop {
289 if let Some(buf) = read_raw_packet_from_buffer::<R>(buffer, compression_threshold)? {
290 return Ok(buf);
292 };
293
294 let bytes = read_and_decrypt_frame(stream, cipher).await?;
295 buffer.get_mut().extend_from_slice(&bytes);
296 }
297}
298pub fn try_read_raw_packet<R>(
301 stream: &mut R,
302 buffer: &mut Cursor<Vec<u8>>,
303 compression_threshold: Option<u32>,
304 cipher: &mut Option<Aes128CfbDec>,
305) -> Result<Option<Box<[u8]>>, Box<ReadPacketError>>
306where
307 R: AsyncRead + Unpin + Send + Sync,
308{
309 loop {
310 if let Some(buf) = read_raw_packet_from_buffer::<R>(buffer, compression_threshold)? {
311 return Ok(Some(buf));
313 };
314 let Some(bytes) = try_read_and_decrypt_frame(stream, cipher)? else {
315 return Ok(None);
317 };
318 buffer.get_mut().extend_from_slice(&bytes);
320 }
321}
322
323async fn read_and_decrypt_frame<R>(
324 stream: &mut R,
325 cipher: &mut Option<Aes128CfbDec>,
326) -> Result<Box<[u8]>, Box<ReadPacketError>>
327where
328 R: AsyncRead + Unpin + Send + Sync,
329{
330 let mut framed = FramedRead::new(stream, BytesCodec::new());
331
332 let Some(message) = framed.next().await else {
333 return Err(Box::new(ReadPacketError::ConnectionClosed));
334 };
335 let bytes = message.map_err(ReadPacketError::from)?;
336
337 let mut bytes = bytes.to_vec().into_boxed_slice();
338
339 if let Some(cipher) = cipher {
341 azalea_crypto::decrypt_packet(cipher, &mut bytes);
342 }
343
344 Ok(bytes)
345}
346fn try_read_and_decrypt_frame<R>(
347 stream: &mut R,
348 cipher: &mut Option<Aes128CfbDec>,
349) -> Result<Option<Box<[u8]>>, Box<ReadPacketError>>
350where
351 R: AsyncRead + Unpin + Send + Sync,
352{
353 let mut framed = FramedRead::new(stream, BytesCodec::new());
354
355 let Some(message) = future::block_on(future::poll_once(framed.next())) else {
356 return Ok(None);
358 };
359 let Some(message) = message else {
360 return Err(Box::new(ReadPacketError::ConnectionClosed));
361 };
362 let bytes = message.map_err(ReadPacketError::from)?;
363 let mut bytes = bytes.to_vec().into_boxed_slice();
364
365 if let Some(cipher) = cipher {
367 azalea_crypto::decrypt_packet(cipher, &mut bytes);
368 }
369
370 Ok(Some(bytes))
371}
372
373pub fn read_raw_packet_from_buffer<R>(
374 buffer: &mut Cursor<Vec<u8>>,
375 compression_threshold: Option<u32>,
376) -> Result<Option<Box<[u8]>>, Box<ReadPacketError>>
377where
378 R: AsyncRead + Unpin + Send + Sync,
379{
380 let Some(mut buf) = frame_splitter(buffer).map_err(ReadPacketError::from)? else {
381 return Ok(None);
383 };
384
385 if let Some(compression_threshold) = compression_threshold {
386 buf = compression_decoder(&mut Cursor::new(&buf[..]), compression_threshold)
387 .map_err(ReadPacketError::from)?;
388 }
389
390 if tracing::enabled!(tracing::Level::TRACE) {
391 static DO_NOT_CUT_OFF_PACKET_LOGS: LazyLock<bool> = LazyLock::new(|| {
392 env::var("AZALEA_DO_NOT_CUT_OFF_PACKET_LOGS")
393 .map(|s| s == "1" || s == "true")
394 .unwrap_or(false)
395 });
396
397 let buf_string: String = {
398 if !*DO_NOT_CUT_OFF_PACKET_LOGS && buf.len() > 500 {
399 let cut_off_buf = &buf[..500];
400 format!("{cut_off_buf:?}...")
401 } else {
402 format!("{buf:?}")
403 }
404 };
405 trace!("Reading packet with bytes: {buf_string}");
406 };
407
408 Ok(Some(buf))
409}
410
411#[cfg(test)]
412mod tests {
413 use std::io::Cursor;
414
415 use azalea_buf::AzBuf as _;
416
417 use crate::{packets::game::ClientboundGamePacket, read::deserialize_packet};
418
419 #[test]
420 fn fuzzed_1() {
421 let _ = deserialize_packet::<ClientboundGamePacket>(
423 Default::default(),
424 &mut Cursor::new([132, 1, 255, 255, 255, 255, 255].as_slice()),
425 );
426 }
427 #[test]
428 fn fuzzed_2() {
429 let _ = deserialize_packet::<ClientboundGamePacket>(
431 Default::default(),
432 &mut Cursor::new([132, 1, 75, 0, 255, 255, 255, 255, 24, 0].as_slice()),
433 );
434 }
435 #[test]
436 fn fuzzed_3() {
437 let _ = deserialize_packet::<ClientboundGamePacket>(
439 Default::default(),
440 &mut Cursor::new(
441 [
442 94, 44, 157, 38, 61, 37, 37, 37, 37, 37, 37, 65, 128, 128, 1, 1, 255, 252, 128,
443 128, 128, 128, 128, 128, 128, 40, 0,
444 ]
445 .as_slice(),
446 ),
447 );
448 }
449 #[test]
450 fn fuzzed_4() {
451 let _ = deserialize_packet::<ClientboundGamePacket>(
453 Default::default(),
454 &mut Cursor::new([94, 94, 70, 52, 0, 6, 0].as_slice()),
455 );
456 }
457 #[test]
458 fn fuzzed_5() {
459 let _ = deserialize_packet::<ClientboundGamePacket>(
461 Default::default(),
462 &mut Cursor::new([94, 94, 70, 52, 0, 6, 0, 6, 0].as_slice()),
463 );
464 }
465 #[test]
466 fn fuzzed_6() {
467 let ctx = azalea_buf::Ctx::default();
468 let _ =
470 simdnbt::owned::Nbt::azalea_read(ctx, &mut Cursor::new([10, 10, 0, 0, 0].as_slice()));
471 }
472}