Skip to main content

ghast_protocol/
packet.rs

1//! Packet traits, raw packets and the per-id interest filter.
2
3use bytes::{Bytes, BytesMut};
4
5use crate::codec::{Decode, DecodeResult, Encode, EncodeResult, McWrite, decode_exact};
6use crate::error::DecodeError;
7
8/// Connection state.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10#[non_exhaustive]
11pub enum State {
12    /// The first packet of every connection.
13    Handshaking,
14    /// Server list ping.
15    Status,
16    /// Login (encryption, compression, login success).
17    Login,
18    /// Configuration (1.20.2+): registries, tags, resource packs, between login and play
19    /// and again whenever the server sends `start_configuration`.
20    Configuration,
21    /// In game.
22    Play,
23}
24
25/// Packet direction.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
27pub enum Direction {
28    /// Server to client.
29    Clientbound,
30    /// Client to server.
31    Serverbound,
32}
33
34/// A typed packet of one version, state and direction.
35pub trait Packet: Encode + Decode {
36    /// Packet id in its state and direction.
37    const ID: i32;
38    /// minecraft-data name (e.g. `"map_chunk"`).
39    const NAME: &'static str;
40    /// Connection state the packet belongs to.
41    const STATE: State;
42    /// Direction of the packet.
43    const DIRECTION: Direction;
44}
45
46/// All packets of one version, state and direction as an enum (generated).
47pub trait PacketSet: Sized {
48    /// Connection state of this set.
49    const STATE: State;
50    /// Direction of this set.
51    const DIRECTION: Direction;
52
53    /// Decodes a raw packet into the matching variant (strict: no trailing bytes).
54    fn decode_raw(raw: &RawPacket) -> DecodeResult<Self>;
55    /// Packet id of this value.
56    fn id(&self) -> i32;
57    /// minecraft-data name of this value.
58    fn name(&self) -> &'static str;
59    /// Encodes the packet body (without the id).
60    fn encode_body(&self, w: &mut BytesMut) -> EncodeResult;
61    /// minecraft-data name for a packet id, if the id is known.
62    fn name_of(id: i32) -> Option<&'static str>;
63}
64
65/// A packet whose body has not been decoded yet.
66///
67/// The body is a zero-copy slice of the received (and, if needed, inflated) frame.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct RawPacket {
70    /// Packet id.
71    pub id: i32,
72    /// Packet body after the id.
73    pub body: Bytes,
74}
75
76impl RawPacket {
77    /// Wraps an id and body.
78    #[inline]
79    pub fn new(id: i32, body: Bytes) -> Self {
80        RawPacket { id, body }
81    }
82
83    /// Decodes the body as packet type `P`; checks the id and that the whole body is used.
84    #[inline]
85    pub fn decode_as<P: Packet>(&self) -> DecodeResult<P> {
86        if self.id != P::ID {
87            return Err(DecodeError::IdMismatch {
88                expected: P::ID,
89                actual: self.id,
90            });
91        }
92        decode_exact(&self.body)
93    }
94
95    /// Encodes a typed packet into a raw packet.
96    pub fn from_packet<P: Packet>(p: &P) -> Result<Self, crate::error::EncodeError> {
97        let mut w = BytesMut::new();
98        p.encode(&mut w)?;
99        Ok(RawPacket::new(P::ID, w.freeze()))
100    }
101}
102
103/// Writes `id` + body of a typed packet (the uncompressed, unframed packet data).
104#[inline]
105pub fn write_packet<P: Packet>(p: &P, w: &mut BytesMut) -> EncodeResult {
106    w.put_varint(P::ID);
107    p.encode(w)
108}
109
110/// Set of packet ids a client wants to receive.
111///
112/// The frame decoder drops packets whose id is not in the filter *before* decoding them
113/// and — when compression is on — after inflating only the few bytes that hold the id.
114/// Ids above 255 are never used by the supported versions and are always accepted.
115#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
116pub struct PacketFilter {
117    bits: [u64; 4],
118}
119
120impl Default for PacketFilter {
121    fn default() -> Self {
122        Self::all()
123    }
124}
125
126impl PacketFilter {
127    /// Accepts every packet.
128    pub const fn all() -> Self {
129        PacketFilter {
130            bits: [u64::MAX; 4],
131        }
132    }
133
134    /// Accepts no packet (ids above 255 excepted).
135    pub const fn none() -> Self {
136        PacketFilter { bits: [0; 4] }
137    }
138
139    /// Returns the filter with `id` accepted.
140    #[must_use]
141    pub const fn with(mut self, id: i32) -> Self {
142        if id >= 0 && id < 256 {
143            self.bits[(id as usize) >> 6] |= 1 << (id & 63);
144        }
145        self
146    }
147
148    /// Returns the filter with `id` dropped.
149    #[must_use]
150    pub const fn without(mut self, id: i32) -> Self {
151        if id >= 0 && id < 256 {
152            self.bits[(id as usize) >> 6] &= !(1 << (id & 63));
153        }
154        self
155    }
156
157    /// Accepts `id`.
158    pub fn insert(&mut self, id: i32) {
159        *self = self.with(id);
160    }
161
162    /// Drops `id`.
163    pub fn remove(&mut self, id: i32) {
164        *self = self.without(id);
165    }
166
167    /// Whether packets with this id are wanted.
168    #[inline]
169    pub const fn contains(&self, id: i32) -> bool {
170        if id < 0 || id >= 256 {
171            return true;
172        }
173        self.bits[(id as usize) >> 6] & (1 << (id & 63)) != 0
174    }
175
176    /// Whether every id is accepted (lets the decoder skip the peek).
177    #[inline]
178    pub const fn is_all(&self) -> bool {
179        self.bits[0] == u64::MAX
180            && self.bits[1] == u64::MAX
181            && self.bits[2] == u64::MAX
182            && self.bits[3] == u64::MAX
183    }
184}
185
186/// The packet set of a state a version does not have (the configuration state before
187/// 1.20.2). Uninhabited: decoding always fails with [`DecodeError::UnknownPacketId`].
188#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
189pub enum NoPackets {}
190
191impl PacketSet for NoPackets {
192    const STATE: State = State::Configuration;
193    const DIRECTION: Direction = Direction::Clientbound;
194
195    fn decode_raw(raw: &RawPacket) -> DecodeResult<Self> {
196        Err(DecodeError::UnknownPacketId(raw.id))
197    }
198    fn id(&self) -> i32 {
199        match *self {}
200    }
201    fn name(&self) -> &'static str {
202        match *self {}
203    }
204    fn encode_body(&self, _: &mut BytesMut) -> EncodeResult {
205        match *self {}
206    }
207    fn name_of(_: i32) -> Option<&'static str> {
208        None
209    }
210}
211
212pub(crate) mod sealed {
213    /// Seals [`super::Version`]: only this crate's generated markers implement it.
214    #[allow(unnameable_types)] // unnameable on purpose: that is what seals the trait
215    pub trait Sealed {}
216}
217
218/// A protocol version: its number and the packet sets of every state and direction.
219///
220/// Implemented by the generated marker types (e.g. [`crate::v1_8::V1_8`]). A
221/// version-agnostic layer can be written generically over `V: Version` and map each
222/// version's packet enums into common events. Sealed: new items can be added without
223/// breaking anyone, so it cannot be implemented outside this crate.
224pub trait Version: sealed::Sealed + Copy + Send + Sync + 'static {
225    /// Protocol number sent in the handshake (47 for 1.8.x, 754 for 1.16.5).
226    const PROTOCOL: i32;
227    /// Human-readable version name (e.g. `"1.8.9"`).
228    const NAME: &'static str;
229    /// Bit layout of packed block positions.
230    const POSITION_LAYOUT: crate::types::PositionLayout;
231    /// This version's row in [`crate::versions::TABLE`].
232    const INFO: &'static crate::versions::ProtocolVersion;
233
234    /// Serverbound handshaking packets.
235    type HandshakingServerbound: PacketSet;
236    /// Clientbound status packets.
237    type StatusClientbound: PacketSet;
238    /// Serverbound status packets.
239    type StatusServerbound: PacketSet;
240    /// Clientbound login packets.
241    type LoginClientbound: PacketSet;
242    /// Serverbound login packets.
243    type LoginServerbound: PacketSet;
244    /// Clientbound configuration packets ([`NoPackets`] before 1.20.2).
245    type ConfigurationClientbound: PacketSet;
246    /// Serverbound configuration packets ([`NoPackets`] before 1.20.2).
247    type ConfigurationServerbound: PacketSet;
248    /// Clientbound play packets.
249    type PlayClientbound: PacketSet;
250    /// Serverbound play packets.
251    type PlayServerbound: PacketSet;
252}
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257
258    #[test]
259    fn filter() {
260        let f = PacketFilter::none().with(0x21).with(200);
261        assert!(f.contains(0x21) && f.contains(200) && !f.contains(0x22));
262        assert!(f.contains(300) && f.contains(-1));
263        assert!(PacketFilter::all().is_all() && !f.is_all());
264        assert!(!PacketFilter::all().without(5).contains(5));
265    }
266}