deepslate-protocol 0.3.1

Minecraft protocol primitives for the Deepslate proxy.
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! Common types used across the Minecraft protocol.

use bytes::{Buf, BufMut};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::varint;

/// Maximum length of a Minecraft protocol string (32767 UTF-16 code units).
const MAX_STRING_LENGTH: usize = 32767;

/// Maximum number of properties allowed in a game profile.
///
/// Vanilla Minecraft profiles only have a handful of properties (typically
/// just `textures`). We cap at 16 to match the protocol's practical limit
/// and prevent a malicious peer from triggering a huge allocation via a
/// crafted `VarInt` count.
const MAX_PROPERTIES: usize = 16;

/// Errors that can occur during protocol operations.
#[derive(Debug, thiserror::Error)]
pub enum ProtocolError {
    /// `VarInt` exceeded the maximum of 5 bytes.
    #[error("VarInt is too long (exceeded 5 bytes)")]
    VarIntTooLong,

    /// Buffer ran out of data unexpectedly.
    #[error("unexpected end of data")]
    UnexpectedEof,

    /// String exceeded the maximum allowed length.
    #[error("string too long: {length} > {max}")]
    StringTooLong {
        /// Actual length of the string.
        length: usize,
        /// Maximum allowed length.
        max: usize,
    },

    /// String contained invalid UTF-8.
    #[error("invalid UTF-8 in string")]
    InvalidUtf8,

    /// Invalid packet ID for the current state.
    #[error("unknown packet ID {id:#04x} in state {state}")]
    UnknownPacket {
        /// The packet ID that was not recognized.
        id: i32,
        /// The current protocol state.
        state: String,
    },

    /// A packet field had an invalid value.
    #[error("invalid packet data: {0}")]
    InvalidData(String),

    /// Zlib decompression failed.
    #[error("zlib decompression failed: {0}")]
    DecompressionFailed(#[from] libdeflater::DecompressionError),

    /// Zlib compression failed.
    #[error("zlib compression failed: {0}")]
    CompressionFailed(#[from] libdeflater::CompressionError),

    /// Declared uncompressed size exceeds the protocol maximum.
    #[error("uncompressed size {size} exceeds maximum {max}")]
    UncompressedSizeTooLarge {
        /// Declared size.
        size: usize,
        /// Maximum allowed.
        max: usize,
    },

    /// Frame too large.
    #[error("frame too large: {size} bytes (max {max})")]
    FrameTooLarge {
        /// Actual frame size.
        size: usize,
        /// Maximum allowed size.
        max: usize,
    },

    /// Read buffer exceeded the maximum allowed size.
    #[error("read buffer overflow: {size} bytes (max {max})")]
    ReadBufferOverflow {
        /// Actual buffer size.
        size: usize,
        /// Maximum allowed size.
        max: usize,
    },

    /// Profile property count exceeded the allowed maximum.
    #[error("property count too large: {count} (max {max})")]
    PropertyCountExceeded {
        /// Declared property count.
        count: i32,
        /// Maximum allowed count.
        max: usize,
    },

    /// Byte array exceeded the maximum allowed length.
    #[error("byte array too long: {length} > {max}")]
    ByteArrayTooLong {
        /// Actual declared length.
        length: usize,
        /// Maximum allowed length.
        max: usize,
    },
}

/// A player's game profile, as returned by the Mojang session server.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GameProfile {
    /// The player's UUID.
    pub id: Uuid,
    /// The player's username.
    pub name: String,
    /// Profile properties (e.g., skin textures).
    pub properties: Vec<ProfileProperty>,
}

/// A single property in a game profile.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProfileProperty {
    /// Property name (e.g., "textures").
    pub name: String,
    /// Base64-encoded property value.
    pub value: String,
    /// Optional base64-encoded signature.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
}

/// Read a Minecraft protocol string (VarInt-prefixed UTF-8).
///
/// # Errors
///
/// Returns an error if the string length is invalid or UTF-8 decoding fails.
pub fn read_string(buf: &mut impl Buf) -> Result<String, ProtocolError> {
    read_string_max(buf, MAX_STRING_LENGTH)
}

/// Read a Minecraft protocol string with a custom maximum length.
///
/// # Errors
///
/// Returns an error if the string length exceeds `max_len` or UTF-8 decoding fails.
#[allow(clippy::cast_sign_loss)]
pub fn read_string_max(buf: &mut impl Buf, max_len: usize) -> Result<String, ProtocolError> {
    let length = varint::read_var_int(buf)? as usize;
    if length > max_len * 4 {
        return Err(ProtocolError::StringTooLong {
            length,
            max: max_len * 4,
        });
    }
    if buf.remaining() < length {
        return Err(ProtocolError::UnexpectedEof);
    }

    // Fast path: if the buffer is contiguous, we can validate UTF-8 in-place
    if buf.chunk().len() >= length {
        let s = std::str::from_utf8(&buf.chunk()[..length])
            .map_err(|_| ProtocolError::InvalidUtf8)?
            .to_owned();
        buf.advance(length);
        return Ok(s);
    }

    // Slow path: non-contiguous buffer requires copying
    let mut data = vec![0u8; length];
    buf.copy_to_slice(&mut data);
    String::from_utf8(data).map_err(|_| ProtocolError::InvalidUtf8)
}

/// Write a Minecraft protocol string (VarInt-prefixed UTF-8).
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
pub fn write_string(buf: &mut impl BufMut, value: &str) {
    let bytes = value.as_bytes();
    varint::write_var_int(buf, bytes.len() as i32);
    buf.put_slice(bytes);
}

/// Read a UUID as two big-endian i64 values (Minecraft format).
///
/// # Errors
///
/// Returns `ProtocolError::UnexpectedEof` if not enough data.
pub fn read_uuid(buf: &mut impl Buf) -> Result<Uuid, ProtocolError> {
    if buf.remaining() < 16 {
        return Err(ProtocolError::UnexpectedEof);
    }
    let most = buf.get_u64();
    let least = buf.get_u64();
    Ok(Uuid::from_u64_pair(most, least))
}

/// Write a UUID as two big-endian i64 values (Minecraft format).
pub fn write_uuid(buf: &mut impl BufMut, uuid: Uuid) {
    let (most, least) = uuid.as_u64_pair();
    buf.put_u64(most);
    buf.put_u64(least);
}

/// Write a game profile's properties array in the Minecraft protocol format.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
pub fn write_properties(buf: &mut impl BufMut, properties: &[ProfileProperty]) {
    varint::write_var_int(buf, properties.len() as i32);
    for prop in properties {
        write_string(buf, &prop.name);
        write_string(buf, &prop.value);
        if let Some(sig) = &prop.signature {
            buf.put_u8(1); // has signature
            write_string(buf, sig);
        } else {
            buf.put_u8(0); // no signature
        }
    }
}

/// Read a game profile's properties array from the Minecraft protocol format.
///
/// # Errors
///
/// Returns `PropertyCountExceeded` if the declared count is negative or
/// exceeds [`MAX_PROPERTIES`]. Returns other protocol errors if the data
/// is malformed.
pub fn read_properties(buf: &mut impl Buf) -> Result<Vec<ProfileProperty>, ProtocolError> {
    let raw_count = varint::read_var_int(buf)?;
    let count = usize::try_from(raw_count)
        .ok()
        .filter(|&n| n <= MAX_PROPERTIES)
        .ok_or(ProtocolError::PropertyCountExceeded {
            count: raw_count,
            max: MAX_PROPERTIES,
        })?;
    let mut properties = Vec::with_capacity(count);
    for _ in 0..count {
        let name = read_string(buf)?;
        let value = read_string(buf)?;
        let has_signature = if buf.remaining() < 1 {
            return Err(ProtocolError::UnexpectedEof);
        } else {
            buf.get_u8() != 0
        };
        let signature = if has_signature {
            Some(read_string(buf)?)
        } else {
            None
        };
        properties.push(ProfileProperty {
            name,
            value,
            signature,
        });
    }
    Ok(properties)
}

/// Write an NBT string tag entry (tag type `0x08`) with the given name and value.
///
/// Wire format: `0x08` (`TAG_String`) + name (u16-prefixed) + value (u16-prefixed).
#[allow(clippy::cast_possible_truncation)]
fn write_nbt_string_tag(buf: &mut impl BufMut, name: &str, value: &str) {
    buf.put_u8(0x08); // TAG_String
    buf.put_u16(name.len() as u16);
    buf.put_slice(name.as_bytes());
    buf.put_u16(value.len() as u16);
    buf.put_slice(value.as_bytes());
}

/// Write a Minecraft text component encoded as network NBT.
///
/// Since 1.20.2 (protocol 764), text components in PLAY and CONFIG state
/// packets use NBT encoding instead of JSON strings. The network NBT format
/// omits the root tag name.
///
/// This writes a minimal compound tag: `{"text": "...", "color": "..."}`.
/// The `color` field is only included if `color` is `Some`.
pub fn write_nbt_text_component(buf: &mut impl BufMut, text: &str, color: Option<&str>) {
    buf.put_u8(0x0A); // TAG_Compound (root, no name in network NBT)
    write_nbt_string_tag(buf, "text", text);
    if let Some(color) = color {
        write_nbt_string_tag(buf, "color", color);
    }
    buf.put_u8(0x00); // TAG_End
}

/// Format a UUID without dashes (Minecraft's "undashed" format).
#[must_use]
pub fn undashed_uuid(uuid: Uuid) -> String {
    uuid.as_simple().to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;

    proptest! {
        #[test]
        fn roundtrip_any_string(s in ".{0,1024}") {
            let mut buf = Vec::new();
            write_string(&mut buf, &s);
            let result = read_string(&mut &buf[..]).unwrap();
            prop_assert_eq!(result, s);
        }

        #[test]
        fn roundtrip_any_uuid(u in any::<u128>()) {
            let uuid = Uuid::from_u128(u);
            let mut buf = Vec::new();
            write_uuid(&mut buf, uuid);
            let result = read_uuid(&mut &buf[..]).unwrap();
            prop_assert_eq!(result, uuid);
        }

        #[test]
        fn roundtrip_any_properties(
            props in prop::collection::vec(
                (
                    ".{0,32}",
                    ".{0,1024}",
                    prop::option::weighted(0.5, ".{0,1024}")
                ).prop_map(|(name, value, signature)| ProfileProperty { name, value, signature }),
                0..4
            )
        ) {
            let mut buf = Vec::new();
            write_properties(&mut buf, &props);
            let result = read_properties(&mut &buf[..]).unwrap();
            prop_assert_eq!(result, props);
        }
    }

    #[test]
    fn test_string_roundtrip() {
        let mut buf = Vec::new();
        write_string(&mut buf, "Hello, Minecraft!");
        let result = read_string(&mut &buf[..]).unwrap();
        assert_eq!(result, "Hello, Minecraft!");
    }

    #[test]
    fn test_string_empty() {
        let mut buf = Vec::new();
        write_string(&mut buf, "");
        let result = read_string(&mut &buf[..]).unwrap();
        assert_eq!(result, "");
    }

    #[test]
    fn test_uuid_roundtrip() {
        let uuid = Uuid::parse_str("069a79f4-44e9-4726-a5be-fca90e38aaf5").unwrap();
        let mut buf = Vec::new();
        write_uuid(&mut buf, uuid);
        assert_eq!(buf.len(), 16);
        let result = read_uuid(&mut &buf[..]).unwrap();
        assert_eq!(result, uuid);
    }

    #[test]
    fn test_properties_roundtrip() {
        let props = vec![
            ProfileProperty {
                name: "textures".to_string(),
                value: "base64data".to_string(),
                signature: Some("sig".to_string()),
            },
            ProfileProperty {
                name: "other".to_string(),
                value: "val".to_string(),
                signature: None,
            },
        ];
        let mut buf = Vec::new();
        write_properties(&mut buf, &props);
        let result = read_properties(&mut &buf[..]).unwrap();
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].name, "textures");
        assert_eq!(result[0].signature.as_deref(), Some("sig"));
        assert_eq!(result[1].signature, None);
    }

    #[test]
    fn test_properties_rejects_huge_count() {
        let mut buf = Vec::new();
        varint::write_var_int(&mut buf, i32::MAX);
        let err = read_properties(&mut &buf[..]).unwrap_err();
        assert!(
            matches!(err, ProtocolError::PropertyCountExceeded { count, max } if count == i32::MAX && max == MAX_PROPERTIES),
            "expected PropertyCountExceeded, got {err:?}"
        );
    }

    #[test]
    fn test_properties_rejects_negative_count() {
        let mut buf = Vec::new();
        varint::write_var_int(&mut buf, -1);
        let err = read_properties(&mut &buf[..]).unwrap_err();
        assert!(
            matches!(err, ProtocolError::PropertyCountExceeded { count, max } if count == -1 && max == MAX_PROPERTIES),
            "expected PropertyCountExceeded, got {err:?}"
        );
    }

    #[test]
    fn test_properties_rejects_count_above_max() {
        let mut buf = Vec::new();
        // One above the limit
        varint::write_var_int(&mut buf, i32::try_from(MAX_PROPERTIES + 1).unwrap());
        let err = read_properties(&mut &buf[..]).unwrap_err();
        assert!(
            matches!(err, ProtocolError::PropertyCountExceeded { .. }),
            "expected PropertyCountExceeded, got {err:?}"
        );
    }

    #[test]
    fn test_properties_accepts_empty() {
        let mut buf = Vec::new();
        varint::write_var_int(&mut buf, 0);
        let result = read_properties(&mut &buf[..]).unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn test_properties_accepts_count_at_max() {
        // Build a buffer with exactly MAX_PROPERTIES valid entries.
        let props: Vec<ProfileProperty> = (0..MAX_PROPERTIES)
            .map(|i| ProfileProperty {
                name: format!("prop{i}"),
                value: format!("val{i}"),
                signature: None,
            })
            .collect();
        let mut buf = Vec::new();
        write_properties(&mut buf, &props);
        let result = read_properties(&mut &buf[..]).unwrap();
        assert_eq!(result.len(), MAX_PROPERTIES);
    }

    #[test]
    fn test_nbt_text_component_simple() {
        let mut buf = Vec::new();
        write_nbt_text_component(&mut buf, "hello", None);
        // TAG_Compound (0x0A), TAG_String (0x08), name "text" (4 bytes), value "hello" (5 bytes), TAG_End (0x00)
        assert_eq!(buf[0], 0x0A); // compound
        assert_eq!(buf[1], 0x08); // string tag
        assert_eq!(&buf[2..4], &[0x00, 0x04]); // name length = 4
        assert_eq!(&buf[4..8], b"text");
        assert_eq!(&buf[8..10], &[0x00, 0x05]); // value length = 5
        assert_eq!(&buf[10..15], b"hello");
        assert_eq!(buf[15], 0x00); // end tag
        assert_eq!(buf.len(), 16);
    }

    #[test]
    fn test_nbt_text_component_with_color() {
        let mut buf = Vec::new();
        write_nbt_text_component(&mut buf, "hi", Some("yellow"));
        assert_eq!(buf[0], 0x0A); // compound
        // First entry: "text" = "hi"
        assert_eq!(buf[1], 0x08);
        assert_eq!(&buf[2..4], &[0x00, 0x04]);
        assert_eq!(&buf[4..8], b"text");
        assert_eq!(&buf[8..10], &[0x00, 0x02]);
        assert_eq!(&buf[10..12], b"hi");
        // Second entry: "color" = "yellow"
        assert_eq!(buf[12], 0x08);
        assert_eq!(&buf[13..15], &[0x00, 0x05]);
        assert_eq!(&buf[15..20], b"color");
        assert_eq!(&buf[20..22], &[0x00, 0x06]);
        assert_eq!(&buf[22..28], b"yellow");
        // End tag
        assert_eq!(buf[28], 0x00);
        assert_eq!(buf.len(), 29);
    }
}