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
|
use crate::packets::ProtocolPacket;
use azalea_buf::McBufVarReadable;
use azalea_buf::{read_varint_async, BufReadError, Readable};
use azalea_crypto::Aes128CfbDec;
use flate2::read::ZlibDecoder;
use std::{
cell::Cell,
io::Read,
pin::Pin,
task::{Context, Poll},
};
use thiserror::Error;
use tokio::io::{AsyncRead, AsyncReadExt};
#[derive(Error, Debug)]
pub enum ReadPacketError {
#[error("Error reading packet {packet_name} ({packet_id}): {source}")]
Parse {
packet_id: u32,
packet_name: String,
source: BufReadError,
},
#[error("Unknown packet id {id} in state {state_name}")]
UnknownPacketId { state_name: String, id: u32 },
#[error("Couldn't read packet id")]
ReadPacketId { source: BufReadError },
#[error("Couldn't decompress packet")]
Decompress {
#[from]
source: DecompressionError,
},
#[error("Frame splitter error")]
FrameSplitter {
#[from]
source: FrameSplitterError,
},
#[error("Leftover data after reading packet {packet_name}: {data:?}")]
LeftoverData { data: Vec<u8>, packet_name: String },
}
#[derive(Error, Debug)]
pub enum FrameSplitterError {
#[error("Couldn't read VarInt length for packet. The previous packet may have been corrupted")]
LengthRead {
#[from]
source: BufReadError,
},
#[error("Io error")]
Io {
#[from]
source: std::io::Error,
},
}
async fn frame_splitter<R: ?Sized>(mut stream: &mut R) -> Result<Vec<u8>, FrameSplitterError>
where
R: AsyncRead + std::marker::Unpin + std::marker::Send,
{
// Packet Length
let length = read_varint_async(&mut stream).await?;
let mut buf = vec![0; length as usize];
stream.read_exact(&mut buf).await?;
Ok(buf)
}
fn packet_decoder<P: ProtocolPacket>(stream: &mut impl Read) -> Result<P, ReadPacketError> {
// Packet ID
let packet_id = stream
.read_varint()
.map_err(|e| ReadPacketError::ReadPacketId { source: e })?;
P::read(packet_id.try_into().unwrap(), stream)
}
// this is always true in multiplayer, false in singleplayer
static VALIDATE_DECOMPRESSED: bool = true;
pub static MAXIMUM_UNCOMPRESSED_LENGTH: u32 = 2097152;
#[derive(Error, Debug)]
pub enum DecompressionError {
#[error("Couldn't read VarInt length for data")]
LengthReadError {
#[from]
source: BufReadError,
},
#[error("Io error")]
Io {
#[from]
source: std::io::Error,
},
#[error("Badly compressed packet - size of {size} is below server threshold of {threshold}")]
BelowCompressionThreshold { size: u32, threshold: u32 },
#[error(
"Badly compressed packet - size of {size} is larger than protocol maximum of {maximum}"
)]
AboveCompressionThreshold { size: u32, maximum: u32 },
}
fn compression_decoder(
stream: &mut impl Read,
compression_threshold: u32,
) -> Result<Vec<u8>, DecompressionError> {
// Data Length
let n = u32::var_read_from(stream)?;
if n == 0 {
// no data size, no compression
let mut buf = vec![];
stream.read_to_end(&mut buf)?;
return Ok(buf);
}
if VALIDATE_DECOMPRESSED {
if n < compression_threshold {
return Err(DecompressionError::BelowCompressionThreshold {
size: n,
threshold: compression_threshold,
});
}
if n > MAXIMUM_UNCOMPRESSED_LENGTH {
return Err(DecompressionError::AboveCompressionThreshold {
size: n,
maximum: MAXIMUM_UNCOMPRESSED_LENGTH,
});
}
}
let mut decoded_buf = vec![];
let mut decoder = ZlibDecoder::new(stream);
decoder.read_to_end(&mut decoded_buf)?;
Ok(decoded_buf)
}
struct EncryptedStream<'a, R>
where
R: AsyncRead + std::marker::Unpin + std::marker::Send,
{
cipher: Cell<&'a mut Option<Aes128CfbDec>>,
stream: &'a mut Pin<&'a mut R>,
}
impl<R> AsyncRead for EncryptedStream<'_, R>
where
R: AsyncRead + Unpin + Send,
{
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut tokio::io::ReadBuf<'_>,
) -> Poll<std::io::Result<()>> {
// i hate this
let polled = self.as_mut().stream.as_mut().poll_read(cx, buf);
match polled {
Poll::Ready(r) => {
// if we don't check for the remaining then we decrypt big packets incorrectly
// (but only on linux and release mode for some reason LMAO)
if buf.remaining() == 0 {
if let Some(cipher) = self.as_mut().cipher.get_mut() {
azalea_crypto::decrypt_packet(cipher, buf.filled_mut());
}
}
match r {
Ok(()) => Poll::Ready(Ok(())),
Err(e) => panic!("{:?}", e),
}
}
Poll::Pending => Poll::Pending,
}
}
}
pub async fn read_packet<'a, P: ProtocolPacket, R>(
stream: &'a mut R,
compression_threshold: Option<u32>,
cipher: &mut Option<Aes128CfbDec>,
) -> Result<P, ReadPacketError>
where
R: AsyncRead + std::marker::Unpin + std::marker::Send + std::marker::Sync,
{
// let start_time = std::time::Instant::now();
// println!("decrypting packet ({}ms)", start_time.elapsed().as_millis());
// if we were given a cipher, decrypt the packet
let mut encrypted_stream = EncryptedStream {
cipher: Cell::new(cipher),
stream: &mut Pin::new(stream),
};
// println!("splitting packet ({}ms)", start_time.elapsed().as_millis());
let mut buf = frame_splitter(&mut encrypted_stream).await?;
if let Some(compression_threshold) = compression_threshold {
// println!(
// "decompressing packet ({}ms)",
// start_time.elapsed().as_millis()
// );
buf = compression_decoder(&mut buf.as_slice(), compression_threshold)?;
}
// println!("decoding packet ({}ms)", start_time.elapsed().as_millis());
let packet = packet_decoder(&mut buf.as_slice())?;
// println!("decoded packet ({}ms)", start_time.elapsed().as_millis());
if !buf.is_empty() {}
Ok(packet)
}
|