reorganize into different crates

Should help to get a more clear view and simplify things
This commit is contained in:
Snowiiii committed 2024-08-02 10:57:38 +02:00
1 parent 5a1d333f02
commit fd9344a512
34 files changed
+258 -170

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
[package]
name = "pumpkin-protocol"
version.workspace = true
edition.workspace = true
[dependencies]
bytes = "1.7"
uuid = "1.10"
serde = { version = "1.0", features = ["derive"] }
# to parse strings to json responses
serde_json = "1.0"
thiserror = "1.0.63"
log = "0.4"
# encryption
aes = "0.8.4"
cfb8 = "0.8.1"
+32
View File
@@ -0,0 +1,32 @@
### Pumpkin Protocol
Contains all Serverbound(Client->Server) and Clientbound(Server->Client) Packets.
The packets are sorted by their folder architecture you find:
Serverbound Packets under:
`server`
Clientbound Packets under:
`client`
Than they both have folders for packets for all their diffrent states:
### States:
**Handshake**: Always the first packet being send from the Client. This begins also determins the next state, usally to indicate if the player thans perform a Status Request, Join the Server or wants to be transfered.
**Status**: Indicates the Client wants to see a Status response (MOTD).
**Login**: The Login sequence. Indicates the Client wants to join to the Server
**Config**: A sequence of Configuration packets beining mostly send from the Server to the Client. (Features, Resource Pack, Server Links...)
**Play**: The final state which indicate the Player is now ready to Join in also used to handle all other Gameplay packets.
### How to add a Packet ?
You can find all Minecraft Java packets at https://wiki.vg/Protocol. There you also can see in which [State](State) they are.
You also can see all the information the Packets has which we can either Write or Read depending if its Serverbound or Clientbound
#### Adding a Serverbound Packet
Serverbound Packets do use the trait `ServerPacket` which has an packet id (use hex) and can read incoming Client packets.
https://wiki.vg/Protocol gives you the Packet structure which you can than read. Feel free to orientate on already existing Packets.
Please use a name structure like `SPacketName` for the struct, The 'S' representing its Serverbound
#### Adding a Clientbound Packet
Clientbound Packets do use the trait `ClientPacket` which has an packet id (use hex) and can write outgoining Server packets.
https://wiki.vg/Protocol gives you the Packet structure which you can than write. Feel free to orientate on already existing Packets.
Please use a name structure like `CPacketName` for the struct, The 'C' representing its Clientbound
+283
View File
@@ -0,0 +1,283 @@
use core::str;
use std::io::{self, Error, ErrorKind};
use bytes::{Buf, BufMut, BytesMut};
use crate::{VarInt, VarLong};
const SEGMENT_BITS: u8 = 0x7F;
const CONTINUE_BIT: u8 = 0x80;
pub struct ByteBuffer {
buffer: BytesMut,
}
impl ByteBuffer {
pub fn empty() -> Self {
Self {
buffer: BytesMut::new(),
}
}
pub fn new(buffer: BytesMut) -> Self {
Self { buffer }
}
pub fn get_var_int(&mut self) -> VarInt {
let mut value: i32 = 0;
let mut position: i32 = 0;
loop {
let read = self.buffer.get_u8();
value |= ((read & SEGMENT_BITS) as i32) << position;
if read & CONTINUE_BIT == 0 {
break;
}
position += 7;
if position >= 32 {
panic!("VarInt is too big");
}
}
value
}
pub fn get_var_long(&mut self) -> VarLong {
let mut value: i64 = 0;
let mut position: i64 = 0;
loop {
let read = self.buffer.get_u8();
value |= ((read & SEGMENT_BITS) as i64) << position;
if read & CONTINUE_BIT == 0 {
break;
}
position += 7;
if position >= 64 {
panic!("VarInt is too big");
}
}
value
}
pub fn get_string(&mut self) -> Result<String, io::Error> {
self.get_string_len(32767)
}
pub fn get_string_len(&mut self, max_size: usize) -> Result<String, io::Error> {
let size = self.get_var_int();
if size as usize > max_size {
return Err(Error::new(
ErrorKind::InvalidData,
"String length is bigger than max size",
));
}
let data = self.buffer.copy_to_bytes(size as usize);
if data.len() > max_size {
return Err(Error::new(
ErrorKind::InvalidData,
"String is bigger than max size",
));
}
match str::from_utf8(&data) {
Ok(string_result) => Ok(string_result.to_string()),
Err(e) => Err(Error::new(ErrorKind::InvalidData, e)),
}
}
pub fn get_bool(&mut self) -> bool {
self.buffer.get_u8() != 0
}
pub fn get_uuid(&mut self) -> uuid::Uuid {
let mut bytes = [0u8; 16];
self.buffer.copy_to_slice(&mut bytes);
uuid::Uuid::from_slice(&bytes).expect("Failed to parse UUID")
}
pub fn put_bool(&mut self, v: bool) {
if v {
self.buffer.put_u8(1);
} else {
self.buffer.put_u8(0);
}
}
pub fn put_uuid(&mut self, v: uuid::Uuid) {
self.buffer.put_slice(v.as_bytes());
}
pub fn put_string(&mut self, val: &str) {
self.put_var_int(val.len() as VarInt);
self.buffer.put(val.as_bytes());
}
pub fn put_string_array(&mut self, array: &[String]) {
for string in array {
self.put_string(string)
}
}
pub fn put_var_int(&mut self, value: VarInt) {
let mut val = value as u32;
for _ in 0..5 {
let mut b: u8 = val as u8 & 0b01111111;
val >>= 7;
if val != 0 {
b |= 0b10000000;
}
self.buffer.put_u8(b);
if val == 0 {
break;
}
}
}
/// Reads a boolean. If true, the closure is called, and the returned value is
/// wrapped in Some. Otherwise, this returns None.
pub fn get_option<T>(&mut self, val: impl FnOnce(&mut Self) -> T) -> Option<T> {
if self.get_bool() {
Some(val(self))
} else {
None
}
}
/// Writes `true` if the option is Some, or `false` if None. If the option is
/// some, then it also calls the `write` closure.
pub fn put_option<T>(&mut self, val: &Option<T>, write: impl FnOnce(&mut Self, &T)) {
self.put_bool(val.is_some());
match val {
Some(v) => write(self, v),
None => {}
}
}
pub fn get_list<T>(&mut self, val: impl Fn(&mut Self) -> T) -> Vec<T> {
let len = self.get_var_int().try_into().unwrap();
let mut list = Vec::with_capacity(len);
for _ in 0..len {
list.push(val(self));
}
list
}
/// Writes a list to the buffer.
pub fn put_list<T>(&mut self, list: &[T], write: impl Fn(&mut Self, &T)) {
self.put_var_int(list.len().try_into().unwrap());
for v in list {
write(self, v);
}
}
pub fn put_varint_arr(&mut self, v: &[i32]) {
self.put_list(v, |p, &v| p.put_var_int(v))
}
/* pub fn get_nbt(&mut self) -> Option<fastnbt::value::Value> {
match crab_nbt::NbtTag::deserialize(self.buf()) {
Ok(v) => Some(v),
Err(err) => None,
}
}
pub fn put_nbt(&mut self, nbt: N) {
self.buffer.put_slice(&nbt.serialize());
}
*/
pub fn buf(&mut self) -> &mut BytesMut {
&mut self.buffer
}
}
// trait
impl ByteBuffer {
pub fn get_u8(&mut self) -> u8 {
self.buffer.get_u8()
}
pub fn get_i8(&mut self) -> i8 {
self.buffer.get_i8()
}
pub fn get_u16(&mut self) -> u16 {
self.buffer.get_u16()
}
pub fn get_i16(&mut self) -> i16 {
self.buffer.get_i16()
}
pub fn get_u32(&mut self) -> u32 {
self.buffer.get_u32()
}
pub fn get_i32(&mut self) -> i32 {
self.buffer.get_i32()
}
pub fn get_u64(&mut self) -> u64 {
self.buffer.get_u64()
}
pub fn get_i64(&mut self) -> i64 {
self.buffer.get_i64()
}
pub fn get_f32(&mut self) -> f32 {
self.buffer.get_f32()
}
pub fn get_f64(&mut self) -> f64 {
self.buffer.get_f64()
}
pub fn put_u8(&mut self, n: u8) {
self.buffer.put_u8(n)
}
pub fn put_i8(&mut self, n: i8) {
self.buffer.put_i8(n)
}
pub fn put_u16(&mut self, n: u16) {
self.buffer.put_u16(n)
}
pub fn put_i16(&mut self, n: i16) {
self.buffer.put_i16(n)
}
pub fn put_u32(&mut self, n: u32) {
self.buffer.put_u32(n)
}
pub fn put_i32(&mut self, n: i32) {
self.buffer.put_i32(n)
}
pub fn put_u64(&mut self, n: u64) {
self.buffer.put_u64(n)
}
pub fn put_i64(&mut self, n: i64) {
self.buffer.put_i64(n)
}
pub fn put_f32(&mut self, n: f32) {
self.buffer.put_f32(n)
}
pub fn copy_to_bytes(&mut self, len: usize) -> bytes::Bytes {
self.buffer.copy_to_bytes(len)
}
pub fn put_slice(&mut self, src: &[u8]) {
self.buffer.put_slice(src)
}
}
+124
View File
@@ -0,0 +1,124 @@
use crate::{bytebuf::ByteBuffer, ClientPacket, KnownPack, VarInt};
pub struct CCookieRequest {
// TODO
}
impl ClientPacket for CCookieRequest {
const PACKET_ID: VarInt = 0x00;
fn write(&self, bytebuf: &mut ByteBuffer) {}
}
pub struct CPluginMessage<'a> {
channel: &'a str,
data: &'a [u8],
}
impl<'a> CPluginMessage<'a> {
pub fn new(channel: &'a str, data: &'a [u8]) -> Self {
Self { channel, data }
}
}
impl<'a> ClientPacket for CPluginMessage<'a> {
const PACKET_ID: VarInt = 0x01;
fn write(&self, bytebuf: &mut ByteBuffer) {
bytebuf.put_string(self.channel);
bytebuf.put_slice(self.data);
}
}
pub struct CConfigDisconnect<'a> {
reason: &'a str,
}
impl<'a> CConfigDisconnect<'a> {
pub fn new(reason: &'a str) -> Self {
Self { reason }
}
}
impl<'a> ClientPacket for CConfigDisconnect<'a> {
const PACKET_ID: VarInt = 0x02;
fn write(&self, bytebuf: &mut ByteBuffer) {
bytebuf.put_string(self.reason);
}
}
pub struct CFinishConfig {}
impl Default for CFinishConfig {
fn default() -> Self {
Self::new()
}
}
impl CFinishConfig {
pub fn new() -> Self {
Self {}
}
}
impl ClientPacket for CFinishConfig {
const PACKET_ID: VarInt = 0x03;
fn write(&self, _bytebuf: &mut ByteBuffer) {}
}
pub struct CKnownPacks<'a> {
known_packs: &'a [KnownPack<'a>],
}
impl<'a> CKnownPacks<'a> {
pub fn new(known_packs: &'a [KnownPack]) -> Self {
Self { known_packs }
}
}
impl<'a> ClientPacket for CKnownPacks<'a> {
const PACKET_ID: VarInt = 0x0E;
fn write(&self, bytebuf: &mut ByteBuffer) {
bytebuf.put_list::<KnownPack>(self.known_packs, |p, v| {
p.put_string(v.namespace);
p.put_string(v.id);
p.put_string(v.version);
});
}
}
pub struct CRegistryData<'a> {
registry_id: &'a str,
entries: &'a [Entry<'a>],
}
impl<'a> CRegistryData<'a> {
pub fn new(registry_id: &'a str, entries: &'a [Entry]) -> Self {
Self {
registry_id,
entries,
}
}
}
pub struct Entry<'a> {
pub entry_id: &'a str,
pub has_data: bool,
pub data: &'a [u8],
}
impl<'a> ClientPacket for CRegistryData<'a> {
const PACKET_ID: VarInt = 0x07;
fn write(&self, bytebuf: &mut ByteBuffer) {
bytebuf.put_string(self.registry_id);
bytebuf.put_list::<Entry>(self.entries, |p, v| {
p.put_string(v.entry_id);
p.put_bool(v.has_data);
p.put_slice(v.data);
});
}
}
+116
View File
@@ -0,0 +1,116 @@
use crate::{bytebuf::ByteBuffer, ClientPacket, VarInt};
pub struct CLoginDisconnect<'a> {
reason: &'a str,
}
impl<'a> CLoginDisconnect<'a> {
pub fn new(reason: &'a str) -> Self {
Self { reason }
}
}
impl<'a> ClientPacket for CLoginDisconnect<'a> {
const PACKET_ID: VarInt = 0x00;
fn write(&self, bytebuf: &mut ByteBuffer) {
bytebuf.put_string(&serde_json::to_string_pretty(&self.reason).unwrap());
}
}
pub struct CEncryptionRequest<'a> {
server_id: &'a str, // 20
public_key: &'a [u8],
verify_token: &'a [u8],
should_authenticate: bool,
}
impl<'a> CEncryptionRequest<'a> {
pub fn new(
server_id: &'a str,
public_key: &'a [u8],
verify_token: &'a [u8],
should_authenticate: bool,
) -> Self {
Self {
server_id,
public_key,
verify_token,
should_authenticate,
}
}
}
impl<'a> ClientPacket for CEncryptionRequest<'a> {
const PACKET_ID: VarInt = 0x01;
fn write(&self, bytebuf: &mut ByteBuffer) {
bytebuf.put_string(self.server_id);
bytebuf.put_var_int(self.public_key.len() as VarInt);
bytebuf.put_slice(self.public_key);
bytebuf.put_var_int(self.verify_token.len() as VarInt);
bytebuf.put_slice(self.verify_token);
bytebuf.put_bool(self.should_authenticate);
}
}
pub struct CSetCompression {
threshold: VarInt,
}
pub struct CLoginSuccess {
pub uuid: uuid::Uuid,
pub username: String, // 16
pub num_of_props: VarInt,
// pub property: Property,
pub strict_error_handling: bool,
}
impl CLoginSuccess {
pub fn new(
uuid: uuid::Uuid,
username: String,
num_of_props: VarInt,
strict_error_handling: bool,
) -> Self {
Self {
uuid,
username,
num_of_props,
strict_error_handling,
}
}
}
pub struct Property {
name: String,
value: String,
is_signed: bool,
signature: Option<String>,
}
impl ClientPacket for CLoginSuccess {
const PACKET_ID: VarInt = 0x02;
fn write(&self, bytebuf: &mut ByteBuffer) {
bytebuf.put_uuid(self.uuid);
bytebuf.put_string(&self.username);
bytebuf.put_var_int(self.num_of_props);
// Todo
bytebuf.put_bool(self.strict_error_handling);
}
}
impl CSetCompression {
pub fn new(threshold: VarInt) -> Self {
Self { threshold }
}
}
impl ClientPacket for CSetCompression {
const PACKET_ID: VarInt = 0x03;
fn write(&self, bytebuf: &mut ByteBuffer) {
bytebuf.put_var_int(self.threshold);
}
}
+7
View File
@@ -0,0 +1,7 @@
// Clientbound Packets
// Server -> Client
//
pub mod config;
pub mod login;
pub mod play;
pub mod status;
+171
View File
@@ -0,0 +1,171 @@
use crate::{bytebuf::ByteBuffer, ClientPacket, VarInt};
pub struct SetHeldItem {
slot: i8,
}
impl SetHeldItem {
pub fn new(slot: i8) -> Self {
Self { slot }
}
}
impl ClientPacket for SetHeldItem {
const PACKET_ID: VarInt = 0x53;
fn write(&self, bytebuf: &mut ByteBuffer) {
bytebuf.put_i8(self.slot);
}
}
pub struct CPlayerAbilities {
flags: i8,
flying_speed: f32,
field_of_view: f32,
}
impl CPlayerAbilities {
pub fn new(flags: i8, flying_speed: f32, field_of_view: f32) -> Self {
Self {
flags,
flying_speed,
field_of_view,
}
}
}
impl ClientPacket for CPlayerAbilities {
const PACKET_ID: VarInt = 0x38;
fn write(&self, bytebuf: &mut ByteBuffer) {
bytebuf.put_i8(self.flags);
bytebuf.put_f32(self.flying_speed);
bytebuf.put_f32(self.field_of_view);
}
}
pub struct CChangeDifficulty {
difficulty: u8,
locked: bool,
}
impl CChangeDifficulty {
pub fn new(difficulty: u8, locked: bool) -> Self {
Self { difficulty, locked }
}
}
impl ClientPacket for CChangeDifficulty {
const PACKET_ID: VarInt = 0x0B;
fn write(&self, bytebuf: &mut ByteBuffer) {
bytebuf.put_u8(self.difficulty);
bytebuf.put_bool(self.locked);
}
}
pub struct CLogin {
entity_id: i32,
is_hardcore: bool,
dimension_count: VarInt,
dimension_names: Vec<String>,
max_players: VarInt,
view_distance: VarInt,
simulated_distance: VarInt,
reduced_debug_info: bool,
enabled_respawn_screen: bool,
limited_crafting: bool,
dimension_type: VarInt,
dimension_name: String,
hashed_seed: i64,
game_mode: u8,
previous_gamemode: i8,
debug: bool,
is_flat: bool,
has_death_loc: bool,
death_dimension_name: Option<String>,
death_loc: Option<String>, // POSITION NOT STRING
portal_cooldown: VarInt,
enforce_secure_chat: bool,
}
impl CLogin {
#[allow(clippy::too_many_arguments)]
pub fn new(
entity_id: i32,
is_hardcore: bool,
dimension_count: VarInt,
dimension_names: Vec<String>,
max_players: VarInt,
view_distance: VarInt,
simulated_distance: VarInt,
reduced_debug_info: bool,
enabled_respawn_screen: bool,
limited_crafting: bool,
dimension_type: VarInt,
dimension_name: String,
hashed_seed: i64,
game_mode: u8,
previous_gamemode: i8,
debug: bool,
is_flat: bool,
has_death_loc: bool,
death_dimension_name: Option<String>,
death_loc: Option<String>,
portal_cooldown: VarInt,
enforce_secure_chat: bool,
) -> Self {
Self {
entity_id,
is_hardcore,
dimension_count,
dimension_names,
max_players,
view_distance,
simulated_distance,
reduced_debug_info,
enabled_respawn_screen,
limited_crafting,
dimension_type,
dimension_name,
hashed_seed,
game_mode,
previous_gamemode,
debug,
is_flat,
has_death_loc,
death_dimension_name,
death_loc,
portal_cooldown,
enforce_secure_chat,
}
}
}
impl ClientPacket for CLogin {
const PACKET_ID: VarInt = 0x2B;
fn write(&self, bytebuf: &mut ByteBuffer) {
bytebuf.put_i32(self.entity_id);
bytebuf.put_bool(self.is_hardcore);
bytebuf.put_var_int(self.dimension_count);
bytebuf.put_string_array(self.dimension_names.as_slice());
bytebuf.put_var_int(self.max_players);
bytebuf.put_var_int(self.view_distance);
bytebuf.put_var_int(self.simulated_distance);
bytebuf.put_bool(self.reduced_debug_info);
bytebuf.put_bool(self.enabled_respawn_screen);
bytebuf.put_bool(self.limited_crafting);
bytebuf.put_var_int(self.dimension_type);
bytebuf.put_string(&self.dimension_name);
bytebuf.put_i64(self.hashed_seed);
bytebuf.put_u8(self.game_mode);
bytebuf.put_i8(self.previous_gamemode);
bytebuf.put_bool(self.debug);
bytebuf.put_bool(self.is_flat);
bytebuf.put_bool(self.has_death_loc);
bytebuf.put_option(&self.death_dimension_name, |buf, v| buf.put_string(v));
bytebuf.put_option(&self.death_loc, |buf, v| buf.put_string(v));
bytebuf.put_var_int(self.portal_cooldown);
bytebuf.put_bool(self.enforce_secure_chat);
}
}
+37
View File
@@ -0,0 +1,37 @@
use crate::{bytebuf::ByteBuffer, ClientPacket, VarInt};
pub struct CPingResponse {
payload: i64, // must responde with the same as in `SPingRequest`
}
impl CPingResponse {
pub fn new(payload: i64) -> Self {
Self { payload }
}
}
impl ClientPacket for CPingResponse {
const PACKET_ID: VarInt = 0x01;
fn write(&self, bytebuf: &mut ByteBuffer) {
bytebuf.put_i64(self.payload);
}
}
pub struct CStatusResponse<'a> {
json_response: &'a str, // 32767
}
impl<'a> CStatusResponse<'a> {
pub fn new(json_response: &'a str) -> Self {
Self { json_response }
}
}
impl<'a> ClientPacket for CStatusResponse<'a> {
const PACKET_ID: VarInt = 0x00;
fn write(&self, bytebuf: &mut ByteBuffer) {
bytebuf.put_string(self.json_response);
}
}
+185
View File
@@ -0,0 +1,185 @@
use std::io::{self, Write};
use bytebuf::ByteBuffer;
use bytes::Buf;
use serde::Serialize;
use thiserror::Error;
pub mod bytebuf;
pub mod client;
pub mod server;
pub mod packet_decoder;
pub mod packet_encoder;
pub const MAX_PACKET_SIZE: i32 = 2097152;
pub type VarInt = i32;
pub type VarLong = i64;
pub struct VarInt32(pub i32);
impl VarInt32 {
/// The maximum number of bytes a `VarInt` could occupy when read from and
/// written to the Minecraft protocol.
pub const MAX_SIZE: usize = 5;
/// Returns the exact number of bytes this varint will write when
/// [`Encode::encode`] is called, assuming no error occurs.
pub const fn written_size(self) -> usize {
match self.0 {
0 => 1,
n => (31 - n.leading_zeros() as usize) / 7 + 1,
}
}
pub fn decode_partial(r: &mut &[u8]) -> Result<i32, VarIntDecodeError> {
let mut val = 0;
for i in 0..Self::MAX_SIZE {
let byte = r.get_u8();
val |= (i32::from(byte) & 0b01111111) << (i * 7);
if byte & 0b10000000 == 0 {
return Ok(val);
}
}
Err(VarIntDecodeError::TooLarge)
}
pub fn encode(&self, mut w: impl Write) -> Result<(), io::Error> {
let x = self.0 as u64;
let stage1 = (x & 0x000000000000007f)
| ((x & 0x0000000000003f80) << 1)
| ((x & 0x00000000001fc000) << 2)
| ((x & 0x000000000fe00000) << 3)
| ((x & 0x00000000f0000000) << 4);
let leading = stage1.leading_zeros();
let unused_bytes = (leading - 1) >> 3;
let bytes_needed = 8 - unused_bytes;
// set all but the last MSBs
let msbs = 0x8080808080808080;
let msbmask = 0xffffffffffffffff >> (((8 - bytes_needed + 1) << 3) - 1);
let merged = stage1 | (msbs & msbmask);
let bytes = merged.to_le_bytes();
w.write_all(unsafe { bytes.get_unchecked(..bytes_needed as usize) })?;
Ok(())
}
pub fn decode(r: &mut &[u8]) -> Result<Self, VarIntDecodeError> {
let mut val = 0;
for i in 0..Self::MAX_SIZE {
let byte = r.get_u8();
val |= (i32::from(byte) & 0b01111111) << (i * 7);
if byte & 0b10000000 == 0 {
return Ok(VarInt32(val));
}
}
Err(VarIntDecodeError::TooLarge)
}
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, Error)]
pub enum VarIntDecodeError {
#[error("incomplete VarInt decode")]
Incomplete,
#[error("VarInt is too large")]
TooLarge,
}
#[derive(Error, Debug)]
pub enum PacketError {
#[error("failed to decode packet ID")]
DecodeID,
#[error("failed to encode packet ID")]
EncodeID,
#[error("failed to write encoded packet")]
EncodeFailedWrite,
#[error("failed to write encoded packet to connection")]
ConnectionWrite,
#[error("packet exceeds maximum length")]
TooLong,
#[error("packet length is out of bounds")]
OutOfBounds,
#[error("malformed packet length VarInt")]
MailformedLength,
}
#[derive(Debug, PartialEq)]
pub enum ConnectionState {
HandShake,
Status,
Login,
Transfer,
Config,
Play,
}
impl ConnectionState {
pub fn from_varint(var_int: VarInt) -> Self {
match var_int {
1 => Self::Status,
2 => Self::Login,
3 => Self::Transfer,
_ => {
log::info!("Unexpected Status {}", var_int);
Self::Status
}
}
}
}
pub struct RawPacket {
pub len: VarInt,
pub id: VarInt,
pub bytebuf: ByteBuffer,
}
pub trait ClientPacket {
const PACKET_ID: VarInt;
fn write(&self, bytebuf: &mut ByteBuffer);
}
pub trait ServerPacket {
const PACKET_ID: VarInt;
fn read(bytebuf: &mut ByteBuffer) -> Self;
}
#[derive(Serialize)]
pub struct StatusResponse {
pub version: Version,
pub players: Players,
pub description: String,
pub favicon: String, // data:image/png;base64,<data>
// Players, favicon ...
}
#[derive(Serialize)]
pub struct Version {
pub name: String,
pub protocol: u32,
}
#[derive(Serialize)]
pub struct Players {
pub max: u32,
pub online: u32,
pub sample: Vec<Sample>,
}
#[derive(Serialize)]
pub struct Sample {
pub name: String,
pub id: String, // uuid
}
pub struct KnownPack<'a> {
pub namespace: &'a str,
pub id: &'a str,
pub version: &'a str,
}
+108
View File
@@ -0,0 +1,108 @@
use aes::cipher::{generic_array::GenericArray, BlockDecryptMut, BlockSizeUser, KeyIvInit};
use bytes::{Buf, BytesMut};
use crate::{
bytebuf::ByteBuffer, PacketError, RawPacket, VarInt32, VarIntDecodeError, MAX_PACKET_SIZE,
};
type Cipher = cfb8::Decryptor<aes::Aes128>;
// Decoder: Client -> Server
#[derive(Default)]
pub struct PacketDecoder {
buf: BytesMut,
cipher: Option<Cipher>,
}
impl PacketDecoder {
pub fn decode(&mut self) -> Result<Option<RawPacket>, PacketError> {
let mut r = &self.buf[..];
let packet_len = match VarInt32::decode_partial(&mut r) {
Ok(len) => len,
Err(VarIntDecodeError::Incomplete) => return Ok(None),
Err(VarIntDecodeError::TooLarge) => Err(PacketError::MailformedLength)?,
};
if !(0..=MAX_PACKET_SIZE).contains(&packet_len) {
Err(PacketError::OutOfBounds)?
}
if r.len() < packet_len as usize {
// Not enough data arrived yet.
return Ok(None);
}
let packet_len_len = VarInt32(packet_len).written_size();
let mut data;
// no compression
self.buf.advance(packet_len_len);
data = self.buf.split_to(packet_len as usize);
r = &data[..];
let packet_id = VarInt32::decode(&mut r)
.map_err(|_| PacketError::DecodeID)?
.0;
data.advance(data.len() - r.len());
dbg!(packet_id);
Ok(Some(RawPacket {
len: packet_len,
id: packet_id,
bytebuf: ByteBuffer::new(data),
}))
}
pub fn enable_encryption(&mut self, key: &[u8; 16]) {
assert!(self.cipher.is_none(), "encryption is already enabled");
let mut cipher = Cipher::new_from_slices(key, key).expect("invalid key");
// Don't forget to decrypt the data we already have.
Self::decrypt_bytes(&mut cipher, &mut self.buf);
self.cipher = Some(cipher);
}
fn decrypt_bytes(cipher: &mut Cipher, bytes: &mut [u8]) {
for chunk in bytes.chunks_mut(Cipher::block_size()) {
let gen_arr = GenericArray::from_mut_slice(chunk);
cipher.decrypt_block_mut(gen_arr);
}
}
pub fn queue_bytes(&mut self, mut bytes: BytesMut) {
if let Some(cipher) = &mut self.cipher {
Self::decrypt_bytes(cipher, &mut bytes);
}
self.buf.unsplit(bytes);
}
pub fn queue_slice(&mut self, bytes: &[u8]) {
let len = self.buf.len();
self.buf.extend_from_slice(bytes);
if let Some(cipher) = &mut self.cipher {
let slice = &mut self.buf[len..];
Self::decrypt_bytes(cipher, slice);
}
}
pub fn take_capacity(&mut self) -> BytesMut {
self.buf.split_off(self.buf.len())
}
pub fn clear(&mut self) {
self.buf.clear()
}
pub fn reserve(&mut self, additional: usize) {
self.buf.reserve(additional);
}
}
+75
View File
@@ -0,0 +1,75 @@
use std::io::Write;
use aes::cipher::{generic_array::GenericArray, BlockEncryptMut, BlockSizeUser, KeyIvInit};
use bytes::{BufMut, BytesMut};
use crate::{
bytebuf::ByteBuffer, ClientPacket, PacketError, VarInt32,
MAX_PACKET_SIZE,
};
type Cipher = cfb8::Encryptor<aes::Aes128>;
// Encoder: Server -> Client
#[derive(Default)]
pub struct PacketEncoder {
buf: BytesMut,
cipher: Option<Cipher>,
}
impl PacketEncoder {
pub fn append_packet<P: ClientPacket>(&mut self, packet: P) -> Result<(), PacketError> {
let start_len = self.buf.len();
let mut writer = (&mut self.buf).writer();
let mut packet_buf = ByteBuffer::empty();
VarInt32(P::PACKET_ID)
.encode(&mut writer)
.map_err(|_| PacketError::EncodeID)?;
packet.write(&mut packet_buf);
writer
.write(packet_buf.buf())
.map_err(|_| PacketError::EncodeFailedWrite)?;
let data_len = self.buf.len() - start_len;
if false { // compression
}
let packet_len = data_len;
if packet_len >= MAX_PACKET_SIZE as usize {
Err(PacketError::TooLong)?
}
let packet_len_size = VarInt32(packet_len as i32).written_size();
self.buf.put_bytes(0, packet_len_size);
self.buf
.copy_within(start_len..start_len + data_len, start_len + packet_len_size);
let front = &mut self.buf[start_len..];
VarInt32(packet_len as i32)
.encode(front)
.map_err(|_| PacketError::EncodeID)?;
Ok(())
}
pub fn enable_encryption(&mut self, key: &[u8; 16]) {
assert!(self.cipher.is_none(), "encryption is already enabled");
self.cipher = Some(Cipher::new_from_slices(key, key).expect("invalid key"));
}
pub fn take(&mut self) -> BytesMut {
if let Some(cipher) = &mut self.cipher {
for chunk in self.buf.chunks_mut(Cipher::block_size()) {
let gen_arr = GenericArray::from_mut_slice(chunk);
cipher.encrypt_block_mut(gen_arr);
}
}
self.buf.split()
}
}
+54
View File
@@ -0,0 +1,54 @@
use crate::{bytebuf::ByteBuffer, ServerPacket, VarInt};
pub struct SClientInformation {
pub locale: String, // 16
pub view_distance: i8,
pub chat_mode: VarInt, // Varint
pub chat_colors: bool,
pub skin_parts: u8,
pub main_hand: VarInt,
pub text_filtering: bool,
pub server_listing: bool,
}
impl ServerPacket for SClientInformation {
const PACKET_ID: VarInt = 0x00;
fn read(bytebuf: &mut ByteBuffer) -> Self {
Self {
locale: bytebuf.get_string_len(16).unwrap(),
view_distance: bytebuf.get_i8(),
chat_mode: bytebuf.get_var_int(),
chat_colors: bytebuf.get_bool(),
skin_parts: bytebuf.get_u8(),
main_hand: bytebuf.get_var_int(),
text_filtering: bytebuf.get_bool(),
server_listing: bytebuf.get_bool(),
}
}
}
pub struct SAcknowledgeFinishConfig {}
impl ServerPacket for SAcknowledgeFinishConfig {
const PACKET_ID: VarInt = 0x03;
fn read(_bytebuf: &mut ByteBuffer) -> Self {
Self {}
}
}
pub struct SKnownPacks {
known_pack_count: VarInt,
// known_packs: &'a [KnownPack]
}
impl ServerPacket for SKnownPacks {
const PACKET_ID: VarInt = 0x07;
fn read(bytebuf: &mut ByteBuffer) -> Self {
Self {
known_pack_count: bytebuf.get_var_int(),
}
}
}
@@ -0,0 +1,21 @@
use crate::{bytebuf::ByteBuffer, ConnectionState, ServerPacket, VarInt};
pub struct SHandShake {
pub protocol_version: VarInt,
pub server_address: String, // 255
pub server_port: u16,
pub next_state: ConnectionState,
}
impl ServerPacket for SHandShake {
const PACKET_ID: VarInt = 0x00;
fn read(bytebuf: &mut ByteBuffer) -> Self {
Self {
protocol_version: bytebuf.get_var_int(),
server_address: bytebuf.get_string_len(255).unwrap(),
server_port: bytebuf.get_u16(),
next_state: ConnectionState::from_varint(bytebuf.get_var_int()),
}
}
}
+72
View File
@@ -0,0 +1,72 @@
use crate::{bytebuf::ByteBuffer, ServerPacket, VarInt};
pub struct SLoginStart {
pub name: String, // 16
pub uuid: uuid::Uuid,
}
impl ServerPacket for SLoginStart {
const PACKET_ID: VarInt = 0x00;
fn read(bytebuf: &mut ByteBuffer) -> Self {
Self {
name: bytebuf.get_string_len(16).unwrap(),
uuid: bytebuf.get_uuid(),
}
}
}
pub struct SEncryptionResponse {
pub shared_secret_length: VarInt,
pub shared_secret: Vec<u8>,
pub verify_token_length: VarInt,
pub verify_token: Vec<u8>,
}
impl ServerPacket for SEncryptionResponse {
const PACKET_ID: VarInt = 0x01;
fn read(bytebuf: &mut ByteBuffer) -> Self {
let shared_secret_length = bytebuf.get_var_int();
let shared_secret = bytebuf.copy_to_bytes(shared_secret_length as usize);
let verify_token_length = bytebuf.get_var_int();
let verify_token = bytebuf.copy_to_bytes(shared_secret_length as usize);
Self {
shared_secret_length,
shared_secret: shared_secret.to_vec(),
verify_token_length,
verify_token: verify_token.to_vec(),
}
}
}
pub struct SLoginPluginResponse<'a> {
message_id: VarInt,
successful: bool,
data: Option<&'a [u8]>,
}
impl<'a> ServerPacket for SLoginPluginResponse<'a> {
const PACKET_ID: VarInt = 0x02;
fn read(bytebuf: &mut ByteBuffer) -> Self {
Self {
message_id: bytebuf.get_var_int(),
successful: bytebuf.get_bool(),
data: None, // TODO
}
}
}
// Acknowledgement to the Login Success packet sent to the server.
pub struct SLoginAcknowledged {
// empty
}
impl ServerPacket for SLoginAcknowledged {
const PACKET_ID: VarInt = 0x03;
fn read(_bytebuf: &mut ByteBuffer) -> Self {
Self {}
}
}
+6
View File
@@ -0,0 +1,6 @@
// Serverbound Packets
// Client -> Server
pub mod config;
pub mod handshake;
pub mod login;
pub mod status;
Whitespace-only changes.
+27
View File
@@ -0,0 +1,27 @@
use crate::{bytebuf::ByteBuffer, ServerPacket, VarInt};
pub struct SStatusRequest {
// empty
}
impl ServerPacket for SStatusRequest {
const PACKET_ID: VarInt = 0x00;
fn read(_bytebuf: &mut ByteBuffer) -> Self {
Self {}
}
}
pub struct SPingRequest {
pub payload: i64,
}
impl ServerPacket for SPingRequest {
const PACKET_ID: VarInt = 0x01;
fn read(bytebuf: &mut ByteBuffer) -> Self {
Self {
payload: bytebuf.get_i64(),
}
}
}