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

+10 -6
View File
@@ -4,32 +4,36 @@ version = "0.1.0"
edition = "2021"
[dependencies]
pumpkin-protocol = { path = "../pumpkin-protocol"}
pumpkin-registry = { path = "../pumpkin-registry"}
# config
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
rand = "0.8.5"
# encryption
rsa = "0.9.6"
rsa-der = "0.3.0"
aes = "0.8.4"
cfb8 = "0.8.1"
flate2 = "1.0.30"
bytes = "1.7"
thiserror = "1.0.63"
# icon loading
base64 = "0.22.1"
image = { version = "0.25", default-features = false, features = ["png"]}
simple_logger = "5.0.0"
log = "0.4"
# networking
mio = { version = "1.0.1", features = ["os-poll", "net"]}
crossbeam-channel = "0.5.13"
uuid = "1.10"
toml = "0.8.17"
fastnbt = { git = "https://github.com/owengage/fastnbt.git" }
fastsnbt = "0.2"
toml = "0.8.19"
+19 -17
View File
@@ -1,19 +1,21 @@
use crate::{
protocol::{
client::{
config::{CFinishConfig, CKnownPacks, CRegistryData, Entry},
login::{CEncryptionRequest, CLoginSuccess},
status::{CPingResponse, CStatusResponse},
},
registry::{DimensionCodec, WolfCodec},
server::{
config::{SAcknowledgeFinishConfig, SClientInformation, SKnownPacks},
handshake::SHandShake,
login::{SEncryptionResponse, SLoginAcknowledged, SLoginPluginResponse, SLoginStart},
status::{SPingRequest, SStatusRequest},
},
ConnectionState, KnownPack,
use pumpkin_protocol::{
client::{
config::{CFinishConfig, CKnownPacks, CRegistryData, Entry},
login::{CEncryptionRequest, CLoginSuccess},
status::{CPingResponse, CStatusResponse},
},
server::{
config::{SAcknowledgeFinishConfig, SClientInformation, SKnownPacks},
handshake::SHandShake,
login::{SEncryptionResponse, SLoginAcknowledged, SLoginPluginResponse, SLoginStart},
status::{SPingRequest, SStatusRequest},
},
ConnectionState, KnownPack,
};
use pumpkin_registry::{DimensionCodec, WolfCodec};
use crate::{
entity::player::{ChatMode, Hand},
server::Server,
};
@@ -150,10 +152,10 @@ impl ClientPacketProcessor for Client {
self.config = Some(PlayerConfig {
locale: client_information.locale,
view_distance: client_information.view_distance,
chat_mode: client_information.chat_mode,
chat_mode: ChatMode::from_varint(client_information.chat_mode),
chat_colors: client_information.chat_colors,
skin_parts: client_information.skin_parts,
main_hand: client_information.main_hand,
main_hand: Hand::from_varint(client_information.main_hand),
text_filtering: client_information.text_filtering,
server_listing: client_information.server_listing,
});
+17 -40
View File
@@ -6,23 +6,23 @@ use std::{
use crate::{
entity::player::{ChatMode, Hand, Player},
protocol::{
client::{config::CConfigDisconnect, login::CLoginDisconnect},
server::{
config::{SAcknowledgeFinishConfig, SClientInformation, SKnownPacks},
handshake::SHandShake,
login::{SEncryptionResponse, SLoginAcknowledged, SLoginPluginResponse, SLoginStart},
status::{SPingRequest, SStatusRequest},
},
ClientPacket, RawPacket,
},
server::Server,
};
use crate::protocol::ConnectionState;
use mio::{event::Event, net::TcpStream, Token};
use packet_decoder::PacketDecoder;
use packet_encoder::PacketEncoder;
use pumpkin_protocol::{
client::{config::CConfigDisconnect, login::CLoginDisconnect},
packet_decoder::PacketDecoder,
packet_encoder::PacketEncoder,
server::{
config::{SAcknowledgeFinishConfig, SClientInformation, SKnownPacks},
handshake::SHandShake,
login::{SEncryptionResponse, SLoginAcknowledged, SLoginPluginResponse, SLoginStart},
status::{SPingRequest, SStatusRequest},
},
ClientPacket, ConnectionState, PacketError, RawPacket, ServerPacket,
};
use rsa::Pkcs1v15Encrypt;
use std::io::Read;
use thiserror::Error;
@@ -30,13 +30,8 @@ use thiserror::Error;
mod client_packet;
mod player_packet;
mod packet_decoder;
mod packet_encoder;
use client_packet::ClientPacketProcessor;
pub const MAX_PACKET_SIZE: i32 = 2097152;
pub struct PlayerConfig {
locale: String, // 16
view_distance: i8,
@@ -133,14 +128,14 @@ impl Client {
dbg!("Handling packet");
let bytebuf = &mut packet.bytebuf;
match self.connection_state {
crate::protocol::ConnectionState::HandShake => match packet.id {
pumpkin_protocol::ConnectionState::HandShake => match packet.id {
SHandShake::PACKET_ID => self.handle_handshake(server, SHandShake::read(bytebuf)),
_ => log::error!(
"Failed to handle packet id {} while in Handshake state",
packet.id
),
},
crate::protocol::ConnectionState::Status => match packet.id {
pumpkin_protocol::ConnectionState::Status => match packet.id {
SStatusRequest::PACKET_ID => {
self.handle_status_request(server, SStatusRequest::read(bytebuf))
}
@@ -152,7 +147,7 @@ impl Client {
packet.id
),
},
crate::protocol::ConnectionState::Login => match packet.id {
pumpkin_protocol::ConnectionState::Login => match packet.id {
SLoginStart::PACKET_ID => {
self.handle_login_start(server, SLoginStart::read(bytebuf))
}
@@ -170,7 +165,7 @@ impl Client {
packet.id
),
},
crate::protocol::ConnectionState::Config => match packet.id {
pumpkin_protocol::ConnectionState::Config => match packet.id {
SClientInformation::PACKET_ID => {
self.handle_client_information(server, SClientInformation::read(bytebuf))
}
@@ -270,24 +265,6 @@ pub enum EncryptionError {
SharedWrongLength,
}
#[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,
}
fn would_block(err: &io::Error) -> bool {
err.kind() == io::ErrorKind::WouldBlock
}
-109
View File
@@ -1,109 +0,0 @@
use aes::cipher::{generic_array::GenericArray, BlockDecryptMut, BlockSizeUser, KeyIvInit};
use bytes::{Buf, BytesMut};
use crate::{
client::{PacketError, MAX_PACKET_SIZE},
protocol::{bytebuf::ByteBuffer, RawPacket, VarInt32, VarIntDecodeError},
};
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);
}
}
-77
View File
@@ -1,77 +0,0 @@
use std::io::Write;
use aes::cipher::{generic_array::GenericArray, BlockEncryptMut, BlockSizeUser, KeyIvInit};
use bytes::{BufMut, BytesMut};
use crate::{
client::MAX_PACKET_SIZE,
protocol::{bytebuf::ByteBuffer, ClientPacket, VarInt32},
};
use super::PacketError;
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()
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
use crate::protocol::VarInt;
use pumpkin_protocol::VarInt;
use super::{Entity, EntityId};
-1
View File
@@ -12,7 +12,6 @@ const SERVER: Token = Token(0);
pub mod client;
pub mod configuration;
pub mod entity;
pub mod protocol;
pub mod server;
pub mod util;
pub mod world;
-283
View File
@@ -1,283 +0,0 @@
use core::str;
use std::io::{self, Error, ErrorKind};
use bytes::{Buf, BufMut, BytesMut};
use crate::protocol::{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
@@ -1,124 +0,0 @@
use crate::protocol::{bytebuf::ByteBuffer, ClientPacket, KnownPack, VarInt};
pub struct CCookieRequest {
// TODO
}
impl ClientPacket for CCookieRequest {
const PACKET_ID: crate::protocol::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: crate::protocol::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: crate::protocol::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
@@ -1,116 +0,0 @@
use crate::protocol::{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
@@ -1,7 +0,0 @@
// Clientbound Packets
// Server -> Client
//
pub mod config;
pub mod login;
pub mod play;
pub mod status;
-174
View File
@@ -1,174 +0,0 @@
use crate::{
entity::player::GameMode,
protocol::{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: GameMode,
previous_gamemode: GameMode,
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: GameMode,
previous_gamemode: GameMode,
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.to_byte() as u8);
bytebuf.put_i8(self.previous_gamemode.to_byte());
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
@@ -1,37 +0,0 @@
use crate::protocol::{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);
}
}
-159
View File
@@ -1,159 +0,0 @@
use std::io::{self, Write};
use bytebuf::ByteBuffer;
use bytes::Buf;
use serde::Serialize;
use thiserror::Error;
pub mod bytebuf;
pub mod registry;
pub mod client;
pub mod server;
pub type VarInt = i32;
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,
}
pub type VarLong = i64;
#[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);
}
#[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,
}
-107
View File
@@ -1,107 +0,0 @@
use crate::protocol::VarInt;
use super::RegistryValue;
use serde::Serialize;
#[derive(Debug, Clone, Serialize)]
pub struct Biome {
has_precipitation: bool,
temperature: f32,
#[serde(skip_serializing_if = "Option::is_none")]
temperature_modifier: Option<String>,
downfall: f32,
effects: BiomeEffects,
}
#[derive(Debug, Clone, Serialize)]
struct BiomeEffects {
fog_color: i32,
water_color: i32,
water_fog_color: i32,
sky_color: i32,
#[serde(skip_serializing_if = "Option::is_none")]
foliage_color: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
grass_color: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
grass_color_modifier: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
particle: Option<Particle>,
#[serde(skip_serializing_if = "Option::is_none")]
ambient_sound: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
mood_sound: Option<MoodSound>,
#[serde(skip_serializing_if = "Option::is_none")]
additions_sound: Option<AdditionsSound>,
#[serde(skip_serializing_if = "Option::is_none")]
music: Option<Music>,
}
#[derive(Debug, Clone, Serialize)]
struct Particle {
options: ParticleOptions,
probability: f32,
}
#[derive(Debug, Clone, Serialize)]
struct ParticleOptions {
typee: String,
#[serde(skip_serializing_if = "Option::is_none")]
value: Option<VarInt>,
}
#[derive(Debug, Clone, Serialize)]
struct MoodSound {
block_search_extent: i32,
offset: f64,
sound: String,
tick_delay: i32,
}
#[derive(Debug, Clone, Serialize)]
struct AdditionsSound {
sound: String,
tick_chance: f64,
}
#[derive(Debug, Clone, Serialize)]
struct Music {
sound: String,
min_delay: i32,
max_delay: i32,
replace_current_music: bool,
}
// 1.20.6 default https://gist.github.com/WinX64/ab8c7a8df797c273b32d3a3b66522906
pub(super) fn all() -> Vec<RegistryValue<Biome>> {
let biome = Biome {
has_precipitation: false,
temperature: 1.0,
temperature_modifier: None,
downfall: 0.0,
effects: BiomeEffects {
fog_color: 0x7FA1FF,
water_color: 0x7FA1FF,
water_fog_color: 0x7FA1FF,
sky_color: 0x7FA1FF,
foliage_color: Some(0x7FA1FF),
grass_color: Some(0x7FA1FF),
grass_color_modifier: None,
particle: None,
ambient_sound: None,
mood_sound: Some(MoodSound {
block_search_extent: 8,
offset: 2.0,
sound: "minecraft:ambient.cave".into(),
tick_delay: 6000,
}),
additions_sound: None,
music: None,
},
};
vec![RegistryValue {
name: "minecraft:plains".into(),
id: 0,
element: biome,
}]
}
@@ -1,31 +0,0 @@
use super::RegistryValue;
use serde::Serialize;
#[derive(Debug, Clone, Serialize)]
pub struct ChatType {
chat: Decoration,
narration: Decoration,
}
#[derive(Debug, Clone, Serialize)]
struct Decoration {
translation_key: String,
// style: Option<>
parameters: Vec<String>,
}
pub(super) fn all() -> Vec<RegistryValue<ChatType>> {
vec![RegistryValue {
name: "minecraft:chat".into(),
id: 0,
element: ChatType {
chat: Decoration {
parameters: vec!["sender".into(), "content".into()],
translation_key: "chat.type.text".into(),
},
narration: Decoration {
parameters: vec!["sender".into(), "content".into()],
translation_key: "chat.type.text.narrate".into(),
},
},
}]
}
@@ -1,83 +0,0 @@
use serde::Serialize;
use super::RegistryValue;
#[derive(Debug, Clone, Serialize)]
pub struct DamageType {
message_id: String,
scaling: String,
exhaustion: f32,
#[serde(skip_serializing_if = "Option::is_none")]
effects: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
death_message_type: Option<String>,
}
const NAMES: &[&str] = &[
"arrow",
"bad_respawn_point",
"cactus",
"cramming",
"dragon_breath",
"drown",
"dry_out",
"explosion",
"fall",
"falling_anvil",
"falling_block",
"falling_stalactite",
"fireball",
"fireworks",
"fly_into_wall",
"freeze",
"generic",
"generic_kill",
"hot_floor",
"in_fire",
"in_wall",
"indirect_magic",
"lava",
"lightning_bolt",
"magic",
"mob_attack",
"mob_attack_no_aggro",
"mob_projectile",
"on_fire",
"out_of_world",
"outside_border",
"player_attack",
"player_explosion",
"sonic_boom",
"spit",
"stalagmite",
"starve",
"sting",
"sweet_berry_bush",
"thorns",
"thrown",
"trident",
"unattributed_fireball",
"wither",
"wither_skull",
];
pub(super) fn all() -> Vec<RegistryValue<DamageType>> {
let mut items: Vec<_> = NAMES
.iter()
.map(|name| RegistryValue {
name: (*name).into(),
id: 0,
element: DamageType {
exhaustion: 0.1,
message_id: "inFire".into(),
scaling: "when_caused_by_living_non_player".into(),
effects: None,
death_message_type: Some("default".into()),
},
})
.collect();
items[1].element.effects = Some("burning".into());
items
}
@@ -1,88 +0,0 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Dimension {
ambient_light: f32,
bed_works: u8,
coordinate_scale: f64,
effects: DimensionEffects,
#[serde(skip_serializing_if = "Option::is_none")]
fixed_time: Option<i64>,
has_ceiling: u8,
has_raids: u8,
has_skylight: u8,
height: i32,
infiniburn: String,
logical_height: i32,
min_y: i32,
monster_spawn_block_light_limit: i32,
monster_spawn_light_level: MonsterSpawnLightLevel,
natural: u8,
piglin_safe: u8,
respawn_anchor_works: u8,
ultrawarm: u8,
}
#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Default, Debug)]
pub enum DimensionEffects {
#[serde(rename = "minecraft:overworld")]
#[default]
Overworld,
#[serde(rename = "minecraft:the_nether")]
TheNether,
#[serde(rename = "minecraft:the_end")]
TheEnd,
}
impl Default for Dimension {
fn default() -> Self {
Self {
ambient_light: 0.0,
bed_works: 1,
coordinate_scale: 1.0,
effects: DimensionEffects::default(),
fixed_time: None,
has_ceiling: 0,
has_raids: 1,
has_skylight: 1,
height: 384,
infiniburn: "#minecraft:infiniburn_overworld".into(),
logical_height: 384,
min_y: -64,
monster_spawn_block_light_limit: 0,
monster_spawn_light_level: MonsterSpawnLightLevel::Tagged(
MonsterSpawnLightLevelTagged::Uniform {
min_inclusive: 7,
max_inclusive: 0,
},
),
natural: 1,
piglin_safe: 0,
respawn_anchor_works: 0,
ultrawarm: 0,
}
}
}
#[derive(Copy, Clone, PartialEq, Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum MonsterSpawnLightLevel {
Int(i32),
Tagged(MonsterSpawnLightLevelTagged),
}
#[derive(Copy, Clone, PartialEq, Debug, Serialize, Deserialize)]
#[serde(tag = "type", content = "value")]
pub enum MonsterSpawnLightLevelTagged {
#[serde(rename = "minecraft:uniform")]
Uniform {
min_inclusive: i32,
max_inclusive: i32,
},
}
impl From<i32> for MonsterSpawnLightLevel {
fn from(value: i32) -> Self {
Self::Int(value)
}
}
-122
View File
@@ -1,122 +0,0 @@
use dimensions::Dimension;
use fastnbt::SerOpts;
use serde::Serialize;
use wolf::WolfVariant;
use super::bytebuf::ByteBuffer;
mod biomes;
mod chat_type;
mod damage_type;
mod dimensions;
mod wolf;
#[derive(Debug, Clone, Serialize)]
struct LoginInfo {
#[serde(rename = "minecraft:dimension_type")]
dimensions: Codec<dimensions::Dimension>,
// #[serde(rename = "minecraft:wolf_variant")]
// wolf: Codec<wolf::WolfVariant>,
/* #[serde(rename = "minecraft:worldgen/biome")]
biomes: Codec<biomes::Biome>,
#[serde(rename = "minecraft:chat_type")]
chat: Codec<chat_type::ChatType>,
#[serde(rename = "minecraft:damage_type")]
damage: Codec<damage_type::DamageType>, */
}
#[derive(Debug, Clone, Serialize)]
pub struct DimensionCodec {
#[serde(rename = "minecraft:dimension_type")]
dimensions: Codec<dimensions::Dimension>,
}
impl DimensionCodec {
pub fn parse() -> Vec<u8> {
let dimension = Dimension::default();
let codec = DimensionCodec {
dimensions: Codec {
ty: "minecraft:dimension_type".into(),
value: vec![RegistryValue {
name: "minecraft:overworld".into(),
id: 0,
element: dimension,
}],
},
};
fastnbt::to_bytes_with_opts(&codec, SerOpts::network_nbt()).unwrap()
}
}
#[derive(Debug, Clone, Serialize)]
pub struct WolfCodec {
#[serde(rename = "minecraft:wolf_variant")]
wolf: Codec<wolf::WolfVariant>,
}
impl WolfCodec {
pub fn parse() -> Vec<u8> {
let wolf = WolfVariant::default();
let codec = WolfCodec {
wolf: Codec {
ty: "minecraft:wolf_variant".into(),
value: vec![RegistryValue {
name: "minecraft:wolf_variant".into(),
id: 0,
element: wolf,
}],
},
};
fastnbt::to_bytes_with_opts(&codec, SerOpts::network_nbt()).unwrap()
}
}
#[derive(Debug, Clone, Serialize)]
struct Codec<T> {
#[serde(rename = "type")]
ty: String,
value: Vec<RegistryValue<T>>,
}
#[derive(Debug, Clone, Serialize)]
struct RegistryValue<T> {
name: String,
id: i32,
element: T,
}
pub fn write_codec(out: &mut ByteBuffer, world_min_y: i32, world_height: u32) -> Vec<u8> {
let dimension = Dimension::default();
let wolf = WolfVariant::default();
let info = LoginInfo {
dimensions: Codec {
ty: "minecraft:dimension_type".into(),
value: vec![RegistryValue {
name: "minecraft:overworld".into(),
id: 0,
element: dimension,
}],
},
/* wolf: Codec {
ty: "minecraft:wolf_variant".into(),
value: vec![RegistryValue {
name: "minecraft:wolf_variant".into(),
id: 0,
element: wolf,
}],
}, */ /* biomes: Codec {
ty: "minecraft:worldgen/biome".into(),
value: biomes::all(),
},
chat: Codec {
ty: "minecraft:chat_type".into(),
value: chat_type::all(),
},
damage: Codec {
ty: "minecraft:damage_type".into(),
value: damage_type::all(),
}, */
};
fastnbt::to_bytes_with_opts(&info, SerOpts::network_nbt()).unwrap()
}
-20
View File
@@ -1,20 +0,0 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WolfVariant {
wild_texture: String,
tame_texture: String,
angry_texture: String,
biomes: String,
}
impl Default for WolfVariant {
fn default() -> Self {
Self {
wild_texture: "minecraft:entity/wolf/wolf_ashen".to_string(),
tame_texture: "minecraft:entity/wolf/wolf_ashen_tame".to_string(),
angry_texture: "minecraft:entity/wolf/wolf_ashen_angry".to_string(),
biomes: "minecraft:snowy_taiga".to_string(),
}
}
}
-57
View File
@@ -1,57 +0,0 @@
use crate::{
entity::player::{ChatMode, Hand},
protocol::{bytebuf::ByteBuffer, VarInt},
};
pub struct SClientInformation {
pub locale: String, // 16
pub view_distance: i8,
pub chat_mode: ChatMode, // Varint
pub chat_colors: bool,
pub skin_parts: u8,
pub main_hand: Hand,
pub text_filtering: bool,
pub server_listing: bool,
}
impl SClientInformation {
pub const PACKET_ID: VarInt = 0x00;
pub fn read(bytebuf: &mut ByteBuffer) -> Self {
Self {
locale: bytebuf.get_string_len(16).unwrap(),
view_distance: bytebuf.get_i8(),
chat_mode: ChatMode::from_varint(bytebuf.get_var_int()),
chat_colors: bytebuf.get_bool(),
skin_parts: bytebuf.get_u8(),
main_hand: Hand::from_varint(bytebuf.get_var_int()),
text_filtering: bytebuf.get_bool(),
server_listing: bytebuf.get_bool(),
}
}
}
pub struct SAcknowledgeFinishConfig {}
impl SAcknowledgeFinishConfig {
pub const PACKET_ID: VarInt = 0x03;
pub fn read(_bytebuf: &mut ByteBuffer) -> Self {
Self {}
}
}
pub struct SKnownPacks {
known_pack_count: VarInt,
// known_packs: &'a [KnownPack]
}
impl SKnownPacks {
pub const PACKET_ID: VarInt = 0x07;
pub fn read(bytebuf: &mut ByteBuffer) -> Self {
Self {
known_pack_count: bytebuf.get_var_int(),
}
}
}
@@ -1,21 +0,0 @@
use crate::protocol::{bytebuf::ByteBuffer, ConnectionState, VarInt};
pub struct SHandShake {
pub protocol_version: VarInt,
pub server_address: String, // 255
pub server_port: u16,
pub next_state: ConnectionState,
}
impl SHandShake {
pub const PACKET_ID: VarInt = 0x00;
pub 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
@@ -1,72 +0,0 @@
use crate::protocol::{bytebuf::ByteBuffer, VarInt};
pub struct SLoginStart {
pub name: String, // 16
pub uuid: uuid::Uuid,
}
impl SLoginStart {
pub const PACKET_ID: VarInt = 0x00;
pub 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 SEncryptionResponse {
pub const PACKET_ID: VarInt = 0x01;
pub 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> SLoginPluginResponse<'a> {
pub const PACKET_ID: VarInt = 0x02;
pub 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 SLoginAcknowledged {
pub const PACKET_ID: VarInt = 0x03;
pub fn read(_bytebuf: &mut ByteBuffer) -> Self {
Self {}
}
}
-6
View File
@@ -1,6 +0,0 @@
// Serverbound Packets
// Client -> Server
pub mod config;
pub mod handshake;
pub mod login;
pub mod status;
Whitespace-only changes.
-27
View File
@@ -1,27 +0,0 @@
use crate::protocol::{bytebuf::ByteBuffer, VarInt};
pub struct SStatusRequest {
// empty
}
impl SStatusRequest {
pub const PACKET_ID: VarInt = 0x00;
pub fn read(_bytebuf: &mut ByteBuffer) -> Self {
Self {}
}
}
pub struct SPingRequest {
pub payload: i64,
}
impl SPingRequest {
pub const PACKET_ID: VarInt = 0x01;
pub fn read(bytebuf: &mut ByteBuffer) -> Self {
Self {
payload: bytebuf.get_i64(),
}
}
}
+7 -7
View File
@@ -5,20 +5,20 @@ use std::{
use base64::{engine::general_purpose, Engine};
use mio::{event::Event, Poll};
use pumpkin_protocol::{
client::{config::CPluginMessage, play::CLogin},
PacketError, Players, Sample, StatusResponse, VarInt, VarInt32, Version,
};
use rsa::{rand_core::OsRng, traits::PublicKeyParts, RsaPrivateKey, RsaPublicKey};
use serde::{Deserialize, Serialize};
use crate::{
client::{Client, PacketError},
client::Client,
configuration::{AdvancedConfiguration, BasicConfiguration},
entity::{
player::{GameMode, Player},
Entity, EntityId,
},
protocol::{
client::{config::CPluginMessage, play::CLogin},
Players, Sample, StatusResponse, VarInt, VarInt32, Version,
},
world::World,
};
@@ -117,8 +117,8 @@ impl Server {
1,
"minecraft:overworld".into(),
0, // seed
GameMode::Survival,
GameMode::Undefined,
GameMode::Survival.to_byte() as u8,
GameMode::Undefined.to_byte(),
false,
false,
false, // deth loc