deepslate 0.1.0

A high-performance Minecraft server proxy written in Rust.
Documentation
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
//! Connection handling: framing, encryption, compression, and the bidirectional
//! packet relay pipeline.

pub mod backend;
pub mod client;
pub mod forwarding;

use std::io;

use aes::Aes128;
use bytes::{Buf, BytesMut};
use cfb8::cipher::generic_array::GenericArray;
use cfb8::cipher::{BlockDecryptMut, BlockEncryptMut, KeyIvInit};
use deepslate_protocol::codec;
use deepslate_protocol::packet::Packet;
use deepslate_protocol::packet::login::SetCompressionPacket;
use deepslate_protocol::varint;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;

type Aes128Cfb8Enc = cfb8::Encryptor<Aes128>;
type Aes128Cfb8Dec = cfb8::Decryptor<Aes128>;

/// AES-CFB8 cipher wrapper that supports incremental encrypt/decrypt across
/// multiple calls (the cfb8 crate's `AsyncStreamCipher::encrypt` consumes self,
/// so we use `BlockEncryptMut`/`BlockDecryptMut` directly).
struct CipherPair {
    encryptor: Aes128Cfb8Enc,
    decryptor: Aes128Cfb8Dec,
}

impl CipherPair {
    fn new(shared_secret: &[u8]) -> Self {
        let key = shared_secret.into();
        let iv = shared_secret.into();
        Self {
            encryptor: Aes128Cfb8Enc::new(key, iv),
            decryptor: Aes128Cfb8Dec::new(key, iv),
        }
    }

    /// Encrypt data in-place, one byte at a time (CFB-8 operates on single bytes).
    fn encrypt(&mut self, data: &mut [u8]) {
        let mut block = GenericArray::default();
        for byte in data.iter_mut() {
            block[0] = *byte;
            self.encryptor.encrypt_block_mut(&mut block);
            *byte = block[0];
        }
    }

    /// Decrypt data in-place, one byte at a time.
    fn decrypt(&mut self, data: &mut [u8]) {
        let mut block = GenericArray::default();
        for byte in data.iter_mut() {
            block[0] = *byte;
            self.decryptor.decrypt_block_mut(&mut block);
            *byte = block[0];
        }
    }
}

/// A Minecraft connection with framing, optional encryption, and optional compression.
pub struct MinecraftConnection {
    /// The underlying TCP stream.
    stream: TcpStream,
    /// Read buffer for accumulating incoming data.
    read_buf: BytesMut,
    /// AES-CFB8 cipher pair (set after encryption handshake).
    cipher: Option<CipherPair>,
    /// Compression threshold (-1 = disabled).
    compression_threshold: i32,
    /// Reusable zlib decompressor (avoids per-packet allocation).
    decompressor: libdeflater::Decompressor,
    /// Reusable zlib compressor (avoids per-packet allocation).
    compressor: libdeflater::Compressor,
    /// Reusable buffer for decompression output.
    decompress_buf: Vec<u8>,
    /// Reusable buffer for compression output.
    compress_buf: Vec<u8>,
    /// Reusable buffer for write framing output.
    write_buf: Vec<u8>,
}

impl MinecraftConnection {
    /// Wrap a raw TCP stream into a Minecraft connection.
    #[must_use]
    pub fn new(stream: TcpStream, compression_level: libdeflater::CompressionLvl) -> Self {
        Self {
            stream,
            read_buf: BytesMut::with_capacity(32768),
            cipher: None,
            compression_threshold: -1,
            decompressor: libdeflater::Decompressor::new(),
            compressor: libdeflater::Compressor::new(compression_level),
            decompress_buf: Vec::new(),
            compress_buf: Vec::new(),
            write_buf: Vec::new(),
        }
    }

    /// Enable AES-CFB8 encryption using the shared secret as both key and IV.
    pub fn enable_encryption(&mut self, shared_secret: &[u8]) {
        self.cipher = Some(CipherPair::new(shared_secret));
    }

    /// Enable compression at the given threshold.
    pub const fn enable_compression(&mut self, threshold: i32) {
        self.compression_threshold = threshold;
    }

    /// Split into owned read/write halves for bidirectional relay.
    pub fn into_split(self) -> (MinecraftReader, MinecraftWriter) {
        let (read_half, write_half) = self.stream.into_split();
        // If encryption is enabled, clone the cipher state for each half.
        // This is safe because CFB-8 encrypt and decrypt operate on independent state.
        let (enc_cipher, dec_cipher) = if let Some(cipher) = self.cipher {
            (
                Some(EncryptCipher(cipher.encryptor)),
                Some(DecryptCipher(cipher.decryptor)),
            )
        } else {
            (None, None)
        };
        (
            MinecraftReader {
                stream: read_half,
                read_buf: self.read_buf,
                cipher: dec_cipher,
            },
            MinecraftWriter {
                stream: write_half,
                cipher: enc_cipher,
            },
        )
    }

    /// Read a single frame from the connection.
    ///
    /// Handles decryption (if enabled) and frame extraction. Returns the raw
    /// frame data (packet ID + payload), or `None` if the connection is closed.
    ///
    /// # Errors
    ///
    /// Returns I/O errors or protocol errors.
    #[allow(clippy::large_stack_arrays)]
    pub async fn read_frame(&mut self) -> io::Result<Option<BytesMut>> {
        loop {
            // Try to extract a frame from the buffer
            if let Some((varint_size, frame_len)) =
                codec::try_read_frame(&self.read_buf).map_err(protocol_err)?
            {
                // Advance past the length prefix, then split off the frame body.
                // split_to() is O(1) — it shares the underlying allocation.
                self.read_buf.advance(varint_size);
                let frame = self.read_buf.split_to(frame_len);

                if self.compression_threshold >= 0 {
                    let (uncompressed_size, payload) =
                        codec::read_compressed_frame(&frame).map_err(protocol_err)?;
                    if uncompressed_size == 0 {
                        // Payload sits within `frame`; copy only the sub-slice
                        // past the compression VarInt. This is one copy instead
                        // of the previous two.
                        return Ok(Some(BytesMut::from(payload)));
                    }
                    // Reuse the decompressor and buffer across packets to avoid
                    // per-packet allocations. The buffer capacity stabilizes
                    // after a few packets.
                    self.decompress_buf.resize(uncompressed_size, 0);
                    self.decompressor
                        .zlib_decompress(payload, &mut self.decompress_buf)
                        .map_err(|e| {
                            protocol_err(
                                deepslate_protocol::types::ProtocolError::CompressionError(
                                    format!("zlib decompression failed: {e}"),
                                ),
                            )
                        })?;
                    return Ok(Some(BytesMut::from(&self.decompress_buf[..])));
                }

                return Ok(Some(frame));
            }

            // Read more data from the network
            if let Some(cipher) = &mut self.cipher {
                // Must use a temp buffer for in-place decryption
                let mut tmp = [0u8; 32768];
                let n = self.stream.read(&mut tmp).await?;
                if n == 0 {
                    return Ok(None);
                }
                cipher.decrypt(&mut tmp[..n]);
                self.read_buf.extend_from_slice(&tmp[..n]);
            } else {
                // Zero-copy: read directly into BytesMut
                let n = self.stream.read_buf(&mut self.read_buf).await?;
                if n == 0 {
                    return Ok(None);
                }
            }
        }
    }

    /// Write a typed packet to the connection.
    ///
    /// # Errors
    ///
    /// Returns I/O errors.
    #[allow(clippy::future_not_send)]
    pub async fn write_packet<P: Packet>(&mut self, packet: &P) -> io::Result<()> {
        let packet_data = codec::encode_packet_data(P::PACKET_ID, |buf| packet.encode(buf));
        self.write_raw_packet(&packet_data).await
    }

    /// Write raw packet data (already has packet ID + payload) to the connection.
    ///
    /// # Errors
    ///
    /// Returns I/O errors.
    #[allow(
        clippy::cast_sign_loss,
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap
    )]
    pub async fn write_raw_packet(&mut self, packet_data: &[u8]) -> io::Result<()> {
        self.write_buf.clear();

        if self.compression_threshold >= 0 {
            if packet_data.len() >= self.compression_threshold as usize {
                // Reuse the compressor and buffer across packets to avoid
                // per-packet allocations. The buffer capacity stabilizes
                // after a few packets.
                let max_size = self.compressor.zlib_compress_bound(packet_data.len());
                self.compress_buf.resize(max_size, 0);
                let actual_size = self
                    .compressor
                    .zlib_compress(packet_data, &mut self.compress_buf)
                    .map_err(|e| {
                        protocol_err(deepslate_protocol::types::ProtocolError::CompressionError(
                            format!("zlib compression failed: {e}"),
                        ))
                    })?;
                codec::write_compressed_frame(
                    &mut self.write_buf,
                    packet_data.len() as i32,
                    &self.compress_buf[..actual_size],
                );
            } else {
                codec::write_compressed_frame(&mut self.write_buf, 0, packet_data);
            }
        } else {
            codec::write_frame(&mut self.write_buf, packet_data);
        }

        // Encrypt the frame if encryption is enabled
        if let Some(cipher) = &mut self.cipher {
            cipher.encrypt(&mut self.write_buf);
        }

        self.stream.write_all(&self.write_buf).await?;
        Ok(())
    }

    /// Send a `SetCompression` packet and enable compression on this connection.
    ///
    /// # Errors
    ///
    /// Returns I/O errors.
    pub async fn set_compression(&mut self, threshold: i32) -> io::Result<()> {
        self.write_packet(&SetCompressionPacket { threshold })
            .await?;
        self.compression_threshold = threshold;
        Ok(())
    }

    /// Gracefully shut down the connection.
    ///
    /// Flushes any buffered data, sends a TCP FIN, and drains the receive
    /// buffer so that unread client data does not cause the kernel to send a
    /// TCP RST when the socket is dropped. Without the drain, the kernel's
    /// `tcp_close` sees unread data and resets the connection, which causes
    /// the peer to discard any packets we just sent (e.g. a disconnect
    /// message).
    ///
    /// # Errors
    ///
    /// Returns I/O errors from flush or shutdown. Errors during the drain
    /// phase are silently ignored (the disconnect packet has already been
    /// sent).
    pub async fn shutdown(&mut self) -> io::Result<()> {
        self.stream.flush().await?;
        self.stream.shutdown().await?;

        // Drain unread data from the receive buffer to prevent TCP RST.
        // After shutdown(Write), the client will eventually see our FIN and
        // stop sending. We read until EOF or a timeout, whichever comes first.
        let drain = async {
            let mut buf = [0u8; 1024];
            loop {
                match self.stream.read(&mut buf).await {
                    Ok(0) | Err(_) => break,
                    Ok(_) => {}
                }
            }
        };
        let _ = tokio::time::timeout(std::time::Duration::from_secs(5), drain).await;

        Ok(())
    }
}

/// Encryption-only cipher wrapper for the write half.
struct EncryptCipher(Aes128Cfb8Enc);

impl EncryptCipher {
    fn encrypt(&mut self, data: &mut [u8]) {
        let mut block = GenericArray::default();
        for byte in data.iter_mut() {
            block[0] = *byte;
            self.0.encrypt_block_mut(&mut block);
            *byte = block[0];
        }
    }
}

/// Decryption-only cipher wrapper for the read half.
struct DecryptCipher(Aes128Cfb8Dec);

impl DecryptCipher {
    fn decrypt(&mut self, data: &mut [u8]) {
        let mut block = GenericArray::default();
        for byte in data.iter_mut() {
            block[0] = *byte;
            self.0.decrypt_block_mut(&mut block);
            *byte = block[0];
        }
    }
}

/// Read half of a split Minecraft connection.
pub struct MinecraftReader {
    stream: tokio::net::tcp::OwnedReadHalf,
    read_buf: BytesMut,
    cipher: Option<DecryptCipher>,
}

impl MinecraftReader {
    /// Read a single raw frame (re-framed: length prefix + inner data).
    ///
    /// Returns the complete wire bytes for one packet, ready to be forwarded.
    /// Returns `None` on connection close.
    ///
    /// # Errors
    ///
    /// Returns I/O or protocol errors.
    #[allow(
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        clippy::large_stack_arrays
    )]
    pub async fn read_raw_frame(&mut self) -> io::Result<Option<Vec<u8>>> {
        loop {
            if let Some((varint_size, frame_len)) =
                codec::try_read_frame(&self.read_buf).map_err(protocol_err)?
            {
                // Re-frame: write a fresh length prefix + the frame body.
                let mut out = Vec::with_capacity(varint_size + frame_len);
                varint::write_var_int(&mut out, frame_len as i32);
                // Advance past the length prefix, then split off the frame
                // body using O(1) split_to instead of copying from Bytes.
                self.read_buf.advance(varint_size);
                let frame = self.read_buf.split_to(frame_len);
                out.extend_from_slice(&frame);
                return Ok(Some(out));
            }

            if let Some(cipher) = &mut self.cipher {
                let mut tmp = [0u8; 32768];
                let n = self.stream.read(&mut tmp).await?;
                if n == 0 {
                    return Ok(None);
                }
                cipher.decrypt(&mut tmp[..n]);
                self.read_buf.extend_from_slice(&tmp[..n]);
            } else {
                let n = self.stream.read_buf(&mut self.read_buf).await?;
                if n == 0 {
                    return Ok(None);
                }
            }
        }
    }
}

/// Write half of a split Minecraft connection.
pub struct MinecraftWriter {
    pub(crate) stream: tokio::net::tcp::OwnedWriteHalf,
    cipher: Option<EncryptCipher>,
}

impl MinecraftWriter {
    /// Write a pre-framed raw packet (as received from the other side).
    ///
    /// # Errors
    ///
    /// Returns I/O errors.
    pub async fn write_raw_frame(&mut self, mut data: Vec<u8>) -> io::Result<()> {
        if let Some(cipher) = &mut self.cipher {
            cipher.encrypt(&mut data);
        }
        self.stream.write_all(&data).await
    }
}

/// Convert a protocol error into an I/O error.
fn protocol_err(e: deepslate_protocol::types::ProtocolError) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidData, e)
}