logo
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
//! Provides low-level access to the Minecraft protocol.
//!
//! You should avoid this module if possible.

use std::io::{Read, Write};
use std::mem;

use anyhow::{anyhow, ensure, Context};
use arrayvec::ArrayVec;
use bitvec::prelude::*;
pub use byte_angle::ByteAngle;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use serde::de::DeserializeOwned;
use serde::Serialize;
use uuid::Uuid;
pub use var_int::VarInt;
pub use var_long::VarLong;
use vek::{Vec2, Vec3, Vec4};

use crate::entity::EntityId;
use crate::nbt;

mod byte_angle;
pub mod codec;
pub mod packets;
mod var_int;
mod var_long;

/// Types that can be written to the Minecraft protocol.
pub trait Encode {
    /// This function must be pure. In other words, consecutive calls to
    /// `encode` must write the exact same sequence of bytes.
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()>;
}

/// Types that can be read from the Minecraft protocol.
pub trait Decode: Sized {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self>;
}

/// The maximum number of bytes in a single packet.
pub const MAX_PACKET_SIZE: i32 = 2097151;

impl Encode for () {
    fn encode(&self, _w: &mut impl Write) -> anyhow::Result<()> {
        Ok(())
    }
}

impl Decode for () {
    fn decode(_r: &mut impl Read) -> anyhow::Result<Self> {
        Ok(())
    }
}

impl<T: Encode, U: Encode> Encode for (T, U) {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        self.0.encode(w)?;
        self.1.encode(w)
    }
}

impl<T: Decode, U: Decode> Decode for (T, U) {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        Ok((T::decode(r)?, U::decode(r)?))
    }
}

impl<T: Encode> Encode for &T {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        (*self).encode(w)
    }
}

impl Encode for bool {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        w.write_u8(*self as u8)?;
        Ok(())
    }
}

impl Decode for bool {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        let n = r.read_u8()?;
        ensure!(n < 2, "boolean is not 0 or 1");
        Ok(n == 1)
    }
}

impl Encode for u8 {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        w.write_u8(*self)?;
        Ok(())
    }
}

impl Decode for u8 {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        Ok(r.read_u8()?)
    }
}

impl Encode for i8 {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        w.write_i8(*self)?;
        Ok(())
    }
}

impl Decode for i8 {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        Ok(r.read_i8()?)
    }
}

impl Encode for u16 {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        w.write_u16::<BigEndian>(*self)?;
        Ok(())
    }
}

impl Decode for u16 {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        Ok(r.read_u16::<BigEndian>()?)
    }
}

impl Encode for i16 {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        w.write_i16::<BigEndian>(*self)?;
        Ok(())
    }
}

impl Decode for i16 {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        Ok(r.read_i16::<BigEndian>()?)
    }
}

impl Encode for u32 {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        w.write_u32::<BigEndian>(*self)?;
        Ok(())
    }
}

impl Decode for u32 {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        Ok(r.read_u32::<BigEndian>()?)
    }
}

impl Encode for i32 {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        w.write_i32::<BigEndian>(*self)?;
        Ok(())
    }
}

impl Decode for i32 {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        Ok(r.read_i32::<BigEndian>()?)
    }
}

impl Encode for u64 {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        w.write_u64::<BigEndian>(*self)?;
        Ok(())
    }
}

impl Decode for u64 {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        Ok(r.read_u64::<BigEndian>()?)
    }
}

impl Encode for i64 {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        w.write_i64::<BigEndian>(*self)?;
        Ok(())
    }
}

impl Decode for i64 {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        Ok(r.read_i64::<BigEndian>()?)
    }
}

impl Encode for f32 {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        ensure!(
            self.is_finite(),
            "attempt to encode non-finite f32 ({})",
            self
        );
        w.write_f32::<BigEndian>(*self)?;
        Ok(())
    }
}
impl Decode for f32 {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        let f = r.read_f32::<BigEndian>()?;
        ensure!(f.is_finite(), "attempt to decode non-finite f32 ({f})");
        Ok(f)
    }
}

impl Encode for f64 {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        ensure!(
            self.is_finite(),
            "attempt to encode non-finite f64 ({})",
            self
        );
        w.write_f64::<BigEndian>(*self)?;
        Ok(())
    }
}

impl Decode for f64 {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        let f = r.read_f64::<BigEndian>()?;
        ensure!(f.is_finite(), "attempt to decode non-finite f64 ({f})");
        Ok(f)
    }
}

impl<T: Encode> Encode for Option<T> {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        match self {
            Some(t) => {
                true.encode(w)?;
                t.encode(w)
            }
            None => false.encode(w),
        }
    }
}

impl<T: Decode> Decode for Option<T> {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        if bool::decode(r)? {
            Ok(Some(T::decode(r)?))
        } else {
            Ok(None)
        }
    }
}

impl<T: Encode> Encode for Box<T> {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        self.as_ref().encode(w)
    }
}

impl<T: Decode> Decode for Box<T> {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        Ok(Box::new(T::decode(r)?))
    }
}

impl Encode for Box<str> {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        encode_string_bounded(self, 0, 32767, w)
    }
}

impl Decode for Box<str> {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        Ok(String::decode(r)?.into_boxed_str())
    }
}

/// An integer with a minimum and maximum value known at compile time. `T` is
/// the underlying integer type.
///
/// If the value is not in bounds, an error is generated while
/// encoding or decoding.
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct BoundedInt<T, const MIN: i64, const MAX: i64>(pub T);

impl<T, const MIN: i64, const MAX: i64> BoundedInt<T, MIN, MAX> {
    pub const fn min_bound(&self) -> i64 {
        MIN
    }

    pub const fn max_bound(&self) -> i64 {
        MAX
    }
}

impl<T, const MIN: i64, const MAX: i64> From<T> for BoundedInt<T, MIN, MAX> {
    fn from(t: T) -> Self {
        Self(t)
    }
}

impl<T, const MIN: i64, const MAX: i64> Encode for BoundedInt<T, MIN, MAX>
where
    T: Encode + Copy + Into<i64>,
{
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        let val = self.0.into();
        ensure!(
            (MIN..=MAX).contains(&val),
            "Integer is not in bounds while encoding (got {val}, expected {MIN}..={MAX})"
        );

        self.0.encode(w)
    }
}

impl<T, const MIN: i64, const MAX: i64> Decode for BoundedInt<T, MIN, MAX>
where
    T: Decode + Copy + Into<i64>,
{
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        let res = T::decode(r)?;
        let val = res.into();

        ensure!(
            (MIN..=MAX).contains(&val),
            "Integer is not in bounds while decoding (got {val}, expected {MIN}..={MAX})"
        );

        Ok(Self(res))
    }
}

impl Encode for String {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        encode_string_bounded(self, 0, 32767, w)
    }
}

impl Decode for String {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        decode_string_bounded(0, 32767, r)
    }
}

/// A string with a minimum and maximum character length known at compile time.
///
/// If the string is not in bounds, an error is generated while
/// encoding or decoding.
///
/// Note that the length is a count of the characters in the string, not bytes.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Default, Hash, Debug)]
pub struct BoundedString<const MIN: usize, const MAX: usize>(pub String);

impl<const MIN: usize, const MAX: usize> BoundedString<MIN, MAX> {
    pub const fn min_bound(&self) -> usize {
        MIN
    }

    pub const fn max_bound(&self) -> usize {
        MAX
    }
}

impl<const MIN: usize, const MAX: usize> Encode for BoundedString<MIN, MAX> {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        encode_string_bounded(&self.0, MIN, MAX, w)
    }
}

impl<const MIN: usize, const MAX: usize> Decode for BoundedString<MIN, MAX> {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        decode_string_bounded(MIN, MAX, r).map(Self)
    }
}

impl<const MIN: usize, const MAX: usize> From<String> for BoundedString<MIN, MAX> {
    fn from(s: String) -> Self {
        Self(s)
    }
}

impl<T: Encode> Encode for Vec<T> {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        encode_array_bounded(self, 0, usize::MAX, w)
    }
}

impl<T: Decode> Decode for Vec<T> {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        decode_array_bounded(0, usize::MAX, r)
    }
}

impl<T: Encode> Encode for Box<[T]> {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        encode_array_bounded(self, 0, usize::MAX, w)
    }
}

impl<T: Decode> Decode for Box<[T]> {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        decode_array_bounded(0, usize::MAX, r).map(|v| v.into_boxed_slice())
    }
}

impl<T: Encode, const N: usize> Encode for [T; N] {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        encode_array_bounded(self, N, N, w)
    }
}

impl<T: Decode, const N: usize> Decode for [T; N] {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        let mut elems = ArrayVec::new();
        for _ in 0..N {
            elems.push(T::decode(r)?);
        }
        elems
            .into_inner()
            .map_err(|_| unreachable!("mismatched array size"))
    }
}

impl<T: Encode> Encode for Vec2<T> {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        self.x.encode(w)?;
        self.y.encode(w)
    }
}

impl<T: Encode> Encode for Vec3<T> {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        self.x.encode(w)?;
        self.y.encode(w)?;
        self.z.encode(w)
    }
}

impl<T: Encode> Encode for Vec4<T> {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        self.x.encode(w)?;
        self.y.encode(w)?;
        self.z.encode(w)?;
        self.w.encode(w)
    }
}

impl<T: Decode> Decode for Vec2<T> {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        Ok(Vec2::new(T::decode(r)?, T::decode(r)?))
    }
}

impl<T: Decode> Decode for Vec3<T> {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        Ok(Vec3::new(T::decode(r)?, T::decode(r)?, T::decode(r)?))
    }
}

impl<T: Decode> Decode for Vec4<T> {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        Ok(Vec4::new(
            T::decode(r)?,
            T::decode(r)?,
            T::decode(r)?,
            T::decode(r)?,
        ))
    }
}

/// An array with a minimum and maximum character length known at compile time.
///
/// If the array is not in bounds, an error is generated while
/// encoding or decoding.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Default, Hash, Debug)]
pub struct BoundedArray<T, const MIN: usize = 0, const MAX: usize = { usize::MAX }>(pub Vec<T>);

impl<T: Encode, const MIN: usize, const MAX: usize> Encode for BoundedArray<T, MIN, MAX> {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        encode_array_bounded(&self.0, MIN, MAX, w)
    }
}

impl<T: Decode, const MIN: usize, const MAX: usize> Decode for BoundedArray<T, MIN, MAX> {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        decode_array_bounded(MIN, MAX, r).map(Self)
    }
}

impl<T, const MIN: usize, const MAX: usize> From<Vec<T>> for BoundedArray<T, MIN, MAX> {
    fn from(v: Vec<T>) -> Self {
        Self(v)
    }
}

impl Encode for Uuid {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        w.write_u128::<BigEndian>(self.as_u128())?;
        Ok(())
    }
}

impl Decode for Uuid {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        Ok(Uuid::from_u128(r.read_u128::<BigEndian>()?))
    }
}

impl Encode for nbt::Compound {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        Ok(nbt::binary::to_writer(w, self)?)
    }
}

impl Decode for nbt::Compound {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        Ok(nbt::binary::from_reader(r)?)
    }
}

/// Wrapper type acting as a bridge between Serde and [Encode]/[Decode] through
/// the NBT format.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Hash, Debug)]
pub struct NbtBridge<T>(pub T);

impl<T: Serialize> Encode for NbtBridge<T> {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        Ok(nbt::binary::to_writer(w, &self.0)?)
    }
}

impl<T: DeserializeOwned> Decode for NbtBridge<T> {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        Ok(Self(nbt::binary::from_reader(r)?))
    }
}

impl Encode for BitVec<u64> {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        encode_array_bounded(self.as_raw_slice(), 0, usize::MAX, w)
    }
}

impl Decode for BitVec<u64> {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        BitVec::try_from_vec(Vec::decode(r)?)
            .map_err(|_| anyhow!("Array is too long for bit vector"))
    }
}

impl Encode for BitBox<u64> {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        encode_array_bounded(self.as_raw_slice(), 0, usize::MAX, w)
    }
}

impl Decode for BitBox<u64> {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        BitVec::decode(r).map(|v| v.into_boxed_bitslice())
    }
}

/// When decoding, reads the rest of the data in a packet and stuffs it into a
/// `Vec<u8>`. When encoding, the data is inserted into the packet with no
/// length prefix.
#[derive(Clone, Debug)]
pub struct RawBytes(pub Vec<u8>);

impl Decode for RawBytes {
    fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
        let mut buf = Vec::new();
        r.read_to_end(&mut buf)?;
        Ok(RawBytes(buf))
    }
}

impl Encode for RawBytes {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        w.write_all(&self.0).map_err(|e| e.into())
    }
}

impl Encode for Option<EntityId> {
    fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
        match self {
            Some(id) => VarInt(
                id.to_network_id()
                    .checked_add(1)
                    .context("i32::MAX is unrepresentable as an optional VarInt")?,
            ),
            None => VarInt(0),
        }
        .encode(w)
    }
}

fn encode_array_bounded<T: Encode>(
    s: &[T],
    min: usize,
    max: usize,
    w: &mut impl Write,
) -> anyhow::Result<()> {
    assert!(min <= max);

    let len = s.len();

    ensure!(
        (min..=max).contains(&len),
        "Length of array is out of bounds while encoding (got {len}, expected {min}..={max})"
    );

    ensure!(
        len <= i32::MAX as usize,
        "Length of array ({len}) exceeds i32::MAX"
    );

    VarInt(len as i32).encode(w)?;
    for t in s {
        t.encode(w)?;
    }
    Ok(())
}

pub(crate) fn encode_string_bounded(
    s: &str,
    min: usize,
    max: usize,
    w: &mut impl Write,
) -> anyhow::Result<()> {
    assert!(min <= max, "Bad min and max");

    let char_count = s.chars().count();

    ensure!(
        (min..=max).contains(&char_count),
        "Char count of string is out of bounds while encoding (got {char_count}, expected \
         {min}..={max})"
    );

    encode_array_bounded(s.as_bytes(), 0, usize::MAX, w)
}

pub(crate) fn decode_string_bounded(
    min: usize,
    max: usize,
    r: &mut impl Read,
) -> anyhow::Result<String> {
    assert!(min <= max);

    let bytes = decode_array_bounded(min, max.saturating_mul(4), r)?;
    let string = String::from_utf8(bytes)?;

    let char_count = string.chars().count();
    ensure!(
        (min..=max).contains(&char_count),
        "Char count of string is out of bounds while decoding (got {char_count}, expected \
         {min}..={max}"
    );

    Ok(string)
}

pub(crate) fn decode_array_bounded<T: Decode>(
    min: usize,
    max: usize,
    r: &mut impl Read,
) -> anyhow::Result<Vec<T>> {
    assert!(min <= max);

    let len = VarInt::decode(r)?.0;
    ensure!(
        len >= 0 && (min..=max).contains(&(len as usize)),
        "Length of array is out of bounds while decoding (got {len}, needed {min}..={max})",
    );

    // Don't allocate more than what would roughly fit in a single packet in case we
    // get a malicious array length.
    let cap = (MAX_PACKET_SIZE as usize / mem::size_of::<T>().max(1)).min(len as usize);

    let mut res = Vec::with_capacity(cap);
    for _ in 0..len {
        res.push(T::decode(r)?);
    }

    Ok(res)
}