Refactor protocol and refactor imports

This commit is contained in:
Vladislavs Golubs 2021-01-24 02:06:31 +03:00
parent 02f2d6b860
commit fca5351977
34 changed files with 598 additions and 1401 deletions

View File

@ -1,4 +1,5 @@
use serde::Serialize;
use std::collections::HashSet;
use std::fmt;
use std::fmt::Display;
@ -9,6 +10,17 @@ pub enum State {
Game,
}
impl State {
pub fn data_import(&self) -> &str {
match self {
State::Handshake => "crate::packet::handshake",
State::Status => "crate::packet::status",
State::Login => "crate::packet::login",
State::Game => "crate::packet::game",
}
}
}
impl Display for State {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let name = match self {
@ -108,6 +120,19 @@ pub enum DataType {
RefType {
ref_name: String,
},
Chat,
}
impl DataType {
pub fn import<'a>(&self, state: &'a State) -> Option<&'a str> {
match self {
DataType::Uuid { .. } => Some("uuid::Uuid"),
DataType::CompoundTag => Some("nbt::CompoundTag"),
DataType::RefType { .. } => Some(state.data_import()),
DataType::Chat => Some("crate::chat::Message"),
_ => None,
}
}
}
pub struct Protocol {
@ -129,21 +154,12 @@ impl Protocol {
}
}
pub fn contains_field_with_type(&self, data_type: DataType) -> bool {
pub fn data_type_imports(&self) -> HashSet<&str> {
self.server_bound_packets
.iter()
.chain(self.client_bound_packets.iter())
.flat_map(|p| p.fields.iter())
.find(|f| f.data_type == data_type)
.is_some()
}
pub fn contains_field_with_predicate<F: Fn(&Field) -> bool>(&self, fun: F) -> bool {
self.server_bound_packets
.iter()
.chain(self.client_bound_packets.iter())
.flat_map(|p| p.fields.iter())
.find(|f| fun(*f))
.is_some()
.filter_map(|f| f.data_type.import(&self.state))
.collect()
}
}

View File

@ -123,16 +123,7 @@ pub fn generate_rust_file<W: Write>(
"minecraft_protocol_derive::Packet",
];
if protocol.contains_field_with_predicate(|f| match f.data_type {
DataType::Uuid { .. } => true,
_ => false,
}) {
imports.push("uuid::Uuid")
}
if protocol.contains_field_with_type(DataType::CompoundTag) {
imports.push("nbt::CompoundTag")
}
imports.extend(protocol.data_type_imports().iter());
template_engine.render_to_write(
"protocol_imports",

View File

@ -6,7 +6,7 @@
//! ## Serialize
//!
//! ```
//! use minecraft_protocol::chat::{Payload, Color, MessageBuilder};
//! use minecraft_protocol::data::chat::{Payload, Color, MessageBuilder};
//!
//! let message = MessageBuilder::builder(Payload::text("Hello"))
//! .color(Color::Yellow)
@ -25,7 +25,7 @@
//! ## Deserialize
//!
//! ```
//! use minecraft_protocol::chat::{MessageBuilder, Color, Payload, Message};
//! use minecraft_protocol::data::chat::{MessageBuilder, Color, Payload, Message};
//!
//! let json = r#"
//! {
@ -93,7 +93,7 @@ pub enum Color {
/// # Examples
///
/// ```
/// use minecraft_protocol::chat::Color;
/// use minecraft_protocol::data::chat::Color;
///
/// let color = Color::Hex("#f98aff".into());
/// ```
@ -444,7 +444,7 @@ fn test_serialize_text_hello_world() {
assert_eq!(
message.to_json().unwrap(),
include_str!("../test/chat/text_hello_world.json")
include_str!("../../test/chat/text_hello_world.json")
);
}
@ -463,7 +463,7 @@ fn test_deserialize_text_hello_world() {
assert_eq!(
expected_message,
Message::from_json(include_str!("../test/chat/text_hello_world.json")).unwrap()
Message::from_json(include_str!("../../test/chat/text_hello_world.json")).unwrap()
);
}
@ -474,7 +474,7 @@ fn test_serialize_translate_opped_steve() {
assert_eq!(
message.to_json().unwrap(),
include_str!("../test/chat/translate_opped_steve.json")
include_str!("../../test/chat/translate_opped_steve.json")
);
}
@ -485,7 +485,7 @@ fn test_deserialize_translate_opped_steve() {
assert_eq!(
expected_message,
Message::from_json(include_str!("../test/chat/translate_opped_steve.json")).unwrap()
Message::from_json(include_str!("../../test/chat/translate_opped_steve.json")).unwrap()
);
}
@ -503,7 +503,7 @@ fn test_serialize_keybind_jump() {
assert_eq!(
message.to_json().unwrap(),
include_str!("../test/chat/keybind_jump.json")
include_str!("../../test/chat/keybind_jump.json")
);
}
@ -521,7 +521,7 @@ fn test_deserialize_keybind_jump() {
assert_eq!(
expected_message,
Message::from_json(include_str!("../test/chat/keybind_jump.json")).unwrap()
Message::from_json(include_str!("../../test/chat/keybind_jump.json")).unwrap()
);
}
@ -535,7 +535,7 @@ fn test_serialize_click_open_url() {
assert_eq!(
message.to_json().unwrap(),
include_str!("../test/chat/click_open_url.json")
include_str!("../../test/chat/click_open_url.json")
);
}
@ -549,7 +549,7 @@ fn test_deserialize_click_open_url() {
assert_eq!(
expected_message,
Message::from_json(include_str!("../test/chat/click_open_url.json")).unwrap()
Message::from_json(include_str!("../../test/chat/click_open_url.json")).unwrap()
);
}
@ -563,7 +563,7 @@ fn test_serialize_click_run_command() {
assert_eq!(
message.to_json().unwrap(),
include_str!("../test/chat/click_run_command.json")
include_str!("../../test/chat/click_run_command.json")
);
}
@ -577,7 +577,7 @@ fn test_deserialize_click_run_command() {
assert_eq!(
expected_message,
Message::from_json(include_str!("../test/chat/click_run_command.json")).unwrap()
Message::from_json(include_str!("../../test/chat/click_run_command.json")).unwrap()
);
}
@ -591,7 +591,7 @@ fn test_serialize_click_suggest_command() {
assert_eq!(
message.to_json().unwrap(),
include_str!("../test/chat/click_suggest_command.json")
include_str!("../../test/chat/click_suggest_command.json")
);
}
@ -605,7 +605,7 @@ fn test_deserialize_click_suggest_command() {
assert_eq!(
expected_message,
Message::from_json(include_str!("../test/chat/click_suggest_command.json")).unwrap()
Message::from_json(include_str!("../../test/chat/click_suggest_command.json")).unwrap()
);
}
@ -619,7 +619,7 @@ fn test_serialize_click_change_page() {
assert_eq!(
message.to_json().unwrap(),
include_str!("../test/chat/click_change_page.json")
include_str!("../../test/chat/click_change_page.json")
);
}
@ -633,7 +633,7 @@ fn test_deserialize_click_change_page() {
assert_eq!(
expected_message,
Message::from_json(include_str!("../test/chat/click_change_page.json")).unwrap()
Message::from_json(include_str!("../../test/chat/click_change_page.json")).unwrap()
);
}
@ -647,7 +647,7 @@ fn test_serialize_hover_show_text() {
assert_eq!(
message.to_json().unwrap(),
include_str!("../test/chat/hover_show_text.json")
include_str!("../../test/chat/hover_show_text.json")
);
}
@ -661,7 +661,7 @@ fn test_deserialize_hover_show_text() {
assert_eq!(
expected_message,
Message::from_json(include_str!("../test/chat/hover_show_text.json")).unwrap()
Message::from_json(include_str!("../../test/chat/hover_show_text.json")).unwrap()
);
}
@ -675,7 +675,7 @@ fn test_serialize_hover_show_item() {
assert_eq!(
message.to_json().unwrap(),
include_str!("../test/chat/hover_show_item.json")
include_str!("../../test/chat/hover_show_item.json")
);
}
@ -689,7 +689,7 @@ fn test_deserialize_hover_show_item() {
assert_eq!(
expected_message,
Message::from_json(include_str!("../test/chat/hover_show_item.json")).unwrap()
Message::from_json(include_str!("../../test/chat/hover_show_item.json")).unwrap()
);
}
@ -703,7 +703,7 @@ fn test_serialize_hover_show_entity() {
assert_eq!(
message.to_json().unwrap(),
include_str!("../test/chat/hover_show_entity.json")
include_str!("../../test/chat/hover_show_entity.json")
);
}
@ -717,7 +717,7 @@ fn test_deserialize_hover_show_entity() {
assert_eq!(
expected_message,
Message::from_json(include_str!("../test/chat/hover_show_entity.json")).unwrap()
Message::from_json(include_str!("../../test/chat/hover_show_entity.json")).unwrap()
);
}
@ -729,7 +729,7 @@ fn test_serialize_hex_color() {
assert_eq!(
message.to_json().unwrap(),
include_str!("../test/chat/hex_color.json")
include_str!("../../test/chat/hex_color.json")
);
}
@ -740,7 +740,7 @@ fn test_deserialize_hex_color() {
.build();
assert_eq!(
Message::from_json(include_str!("../test/chat/hex_color.json")).unwrap(),
Message::from_json(include_str!("../../test/chat/hex_color.json")).unwrap(),
expected_message
);
}

22
protocol/src/data/game.rs Normal file
View File

@ -0,0 +1,22 @@
use crate::impl_enum_encoder_decoder;
use num_derive::{FromPrimitive, ToPrimitive};
#[derive(Debug, Eq, PartialEq, FromPrimitive, ToPrimitive)]
pub enum MessagePosition {
Chat,
System,
HotBar,
}
impl_enum_encoder_decoder!(MessagePosition);
#[derive(Debug, Eq, PartialEq, FromPrimitive, ToPrimitive)]
pub enum GameMode {
Survival = 0,
Creative = 1,
Adventure = 2,
Spectator = 3,
Hardcore = 8,
}
impl_enum_encoder_decoder!(GameMode);

3
protocol/src/data/mod.rs Normal file
View File

@ -0,0 +1,3 @@
pub mod chat;
pub mod game;
pub mod status;

View File

@ -0,0 +1,32 @@
use crate::data::chat::Message;
use crate::impl_json_encoder_decoder;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Serialize, Deserialize, Debug)]
pub struct ServerVersion {
pub name: String,
pub protocol: u32,
}
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
pub struct OnlinePlayer {
pub name: String,
pub id: Uuid,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct OnlinePlayers {
pub max: u32,
pub online: u32,
pub sample: Vec<OnlinePlayer>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ServerStatus {
pub version: ServerVersion,
pub players: OnlinePlayers,
pub description: Message,
}
impl_json_encoder_decoder!(ServerStatus);

106
protocol/src/error.rs Normal file
View File

@ -0,0 +1,106 @@
use nbt::decode::TagDecodeError;
use serde_json::error::Error as JsonError;
use std::io::Error as IoError;
use std::string::FromUtf8Error;
use uuid::parser::ParseError as UuidParseError;
/// Possible errors while encoding packet.
#[derive(Debug)]
pub enum EncodeError {
/// String length can't be more than provided value.
StringTooLong {
/// String length.
length: usize,
/// Max string length.
max_length: u16,
},
IOError {
io_error: IoError,
},
JsonError {
json_error: JsonError,
},
}
impl From<IoError> for EncodeError {
fn from(io_error: IoError) -> Self {
EncodeError::IOError { io_error }
}
}
impl From<JsonError> for EncodeError {
fn from(json_error: JsonError) -> Self {
EncodeError::JsonError { json_error }
}
}
/// Possible errors while decoding packet.
#[derive(Debug)]
pub enum DecodeError {
/// Packet was not recognized. Invalid data or wrong protocol version.
UnknownPacketType {
type_id: u8,
},
/// String length can't be more than provided value.
StringTooLong {
/// String length.
length: usize,
/// Max string length.
max_length: u16,
},
IOError {
io_error: IoError,
},
JsonError {
json_error: JsonError,
},
/// Byte array was not recognized as valid UTF-8 string.
Utf8Error {
utf8_error: FromUtf8Error,
},
/// Boolean are parsed from byte. Valid byte value are 0 or 1.
NonBoolValue,
UuidParseError {
uuid_parse_error: UuidParseError,
},
// Type id was not parsed as valid enum value.
UnknownEnumType {
type_id: u8,
},
TagDecodeError {
tag_decode_error: TagDecodeError,
},
VarIntTooLong {
max_bytes: usize,
},
}
impl From<IoError> for DecodeError {
fn from(io_error: IoError) -> Self {
DecodeError::IOError { io_error }
}
}
impl From<JsonError> for DecodeError {
fn from(json_error: JsonError) -> Self {
DecodeError::JsonError { json_error }
}
}
impl From<FromUtf8Error> for DecodeError {
fn from(utf8_error: FromUtf8Error) -> Self {
DecodeError::Utf8Error { utf8_error }
}
}
impl From<UuidParseError> for DecodeError {
fn from(uuid_parse_error: UuidParseError) -> Self {
DecodeError::UuidParseError { uuid_parse_error }
}
}
impl From<TagDecodeError> for DecodeError {
fn from(tag_decode_error: TagDecodeError) -> Self {
DecodeError::TagDecodeError { tag_decode_error }
}
}

View File

@ -1,504 +0,0 @@
use num_derive::{FromPrimitive, ToPrimitive};
use crate::chat::Message;
use crate::impl_enum_encoder_decoder;
use crate::DecodeError;
use crate::Decoder;
use minecraft_protocol_derive::Packet;
use nbt::CompoundTag;
use std::io::Read;
pub enum GameServerBoundPacket {
ServerBoundChatMessage(ServerBoundChatMessage),
ServerBoundKeepAlive(ServerBoundKeepAlive),
}
pub enum GameClientBoundPacket {
ClientBoundChatMessage(ClientBoundChatMessage),
JoinGame(JoinGame),
ClientBoundKeepAlive(ClientBoundKeepAlive),
ChunkData(ChunkData),
GameDisconnect(GameDisconnect),
}
impl GameServerBoundPacket {
pub fn get_type_id(&self) -> u8 {
match self {
GameServerBoundPacket::ServerBoundChatMessage(_) => 0x03,
GameServerBoundPacket::ServerBoundKeepAlive(_) => 0x0F,
}
}
pub fn decode<R: Read>(type_id: u8, reader: &mut R) -> Result<Self, DecodeError> {
match type_id {
0x03 => {
let chat_message = ServerBoundChatMessage::decode(reader)?;
Ok(GameServerBoundPacket::ServerBoundChatMessage(chat_message))
}
0x0F => {
let keep_alive = ServerBoundKeepAlive::decode(reader)?;
Ok(GameServerBoundPacket::ServerBoundKeepAlive(keep_alive))
}
_ => Err(DecodeError::UnknownPacketType { type_id }),
}
}
}
impl GameClientBoundPacket {
pub fn get_type_id(&self) -> u8 {
match self {
GameClientBoundPacket::ClientBoundChatMessage(_) => 0x0E,
GameClientBoundPacket::GameDisconnect(_) => 0x1A,
GameClientBoundPacket::ClientBoundKeepAlive(_) => 0x20,
GameClientBoundPacket::ChunkData(_) => 0x21,
GameClientBoundPacket::JoinGame(_) => 0x25,
}
}
pub fn decode<R: Read>(type_id: u8, reader: &mut R) -> Result<Self, DecodeError> {
match type_id {
0x0E => {
let chat_message = ClientBoundChatMessage::decode(reader)?;
Ok(GameClientBoundPacket::ClientBoundChatMessage(chat_message))
}
0x1A => {
let game_disconnect = GameDisconnect::decode(reader)?;
Ok(GameClientBoundPacket::GameDisconnect(game_disconnect))
}
0x20 => {
let keep_alive = ClientBoundKeepAlive::decode(reader)?;
Ok(GameClientBoundPacket::ClientBoundKeepAlive(keep_alive))
}
0x21 => {
let chunk_data = ChunkData::decode(reader)?;
Ok(GameClientBoundPacket::ChunkData(chunk_data))
}
0x25 => {
let join_game = JoinGame::decode(reader)?;
Ok(GameClientBoundPacket::JoinGame(join_game))
}
_ => Err(DecodeError::UnknownPacketType { type_id }),
}
}
}
#[derive(Packet, Debug)]
pub struct ServerBoundChatMessage {
#[packet(max_length = 256)]
pub message: String,
}
impl ServerBoundChatMessage {
pub fn new(message: String) -> GameServerBoundPacket {
let chat_message = ServerBoundChatMessage { message };
GameServerBoundPacket::ServerBoundChatMessage(chat_message)
}
}
#[derive(Packet, Debug)]
pub struct ClientBoundChatMessage {
pub message: Message,
pub position: MessagePosition,
}
#[derive(Debug, Eq, PartialEq, FromPrimitive, ToPrimitive)]
pub enum MessagePosition {
Chat,
System,
HotBar,
}
impl_enum_encoder_decoder!(MessagePosition);
impl ClientBoundChatMessage {
pub fn new(message: Message, position: MessagePosition) -> GameClientBoundPacket {
let chat_message = ClientBoundChatMessage { message, position };
GameClientBoundPacket::ClientBoundChatMessage(chat_message)
}
}
#[derive(Packet, Debug)]
pub struct JoinGame {
pub entity_id: u32,
pub game_mode: GameMode,
pub dimension: i32,
pub max_players: u8,
#[packet(max_length = 16)]
pub level_type: String,
#[packet(with = "var_int")]
pub view_distance: i32,
pub reduced_debug_info: bool,
}
#[derive(Debug, Eq, PartialEq, FromPrimitive, ToPrimitive)]
pub enum GameMode {
Survival = 0,
Creative = 1,
Adventure = 2,
Spectator = 3,
Hardcore = 8,
}
impl_enum_encoder_decoder!(GameMode);
impl JoinGame {
pub fn new(
entity_id: u32,
game_mode: GameMode,
dimension: i32,
max_players: u8,
level_type: String,
view_distance: i32,
reduced_debug_info: bool,
) -> GameClientBoundPacket {
let join_game = JoinGame {
entity_id,
game_mode,
dimension,
max_players,
level_type,
view_distance,
reduced_debug_info,
};
GameClientBoundPacket::JoinGame(join_game)
}
}
#[derive(Packet)]
pub struct ServerBoundKeepAlive {
pub id: u64,
}
impl ServerBoundKeepAlive {
pub fn new(id: u64) -> GameServerBoundPacket {
let keep_alive = ServerBoundKeepAlive { id };
GameServerBoundPacket::ServerBoundKeepAlive(keep_alive)
}
}
#[derive(Packet)]
pub struct ClientBoundKeepAlive {
pub id: u64,
}
impl ClientBoundKeepAlive {
pub fn new(id: u64) -> GameClientBoundPacket {
let keep_alive = ClientBoundKeepAlive { id };
GameClientBoundPacket::ClientBoundKeepAlive(keep_alive)
}
}
#[derive(Packet, Debug)]
pub struct ChunkData {
pub x: i32,
pub z: i32,
pub full: bool,
#[packet(with = "var_int")]
pub primary_mask: i32,
pub heights: CompoundTag,
pub data: Vec<u8>,
pub tiles: Vec<CompoundTag>,
}
impl ChunkData {
pub fn new(
x: i32,
z: i32,
full: bool,
primary_mask: i32,
heights: CompoundTag,
data: Vec<u8>,
tiles: Vec<CompoundTag>,
) -> GameClientBoundPacket {
let chunk_data = ChunkData {
x,
z,
full,
primary_mask,
heights,
data,
tiles,
};
GameClientBoundPacket::ChunkData(chunk_data)
}
}
#[derive(Packet, Debug)]
pub struct GameDisconnect {
pub reason: Message,
}
impl GameDisconnect {
pub fn new(reason: Message) -> GameClientBoundPacket {
let game_disconnect = GameDisconnect { reason };
GameClientBoundPacket::GameDisconnect(game_disconnect)
}
}
#[cfg(test)]
mod tests {
use crate::chat::{Message, Payload};
use crate::game::{
ChunkData, ClientBoundChatMessage, ClientBoundKeepAlive, GameDisconnect, GameMode,
JoinGame, MessagePosition, ServerBoundChatMessage, ServerBoundKeepAlive,
};
use crate::{DecodeError, Encoder, EncoderWriteExt, STRING_MAX_LENGTH};
use crate::{Decoder, EncodeError};
use nbt::CompoundTag;
use std::io::Cursor;
#[test]
fn test_server_bound_chat_message_encode() {
let chat_message = ServerBoundChatMessage {
message: String::from("hello server!"),
};
let mut vec = Vec::new();
chat_message.encode(&mut vec).unwrap();
assert_eq!(
vec,
include_bytes!("../test/packet/game/server_bound_chat_message.dat").to_vec()
);
}
#[test]
fn test_server_bound_chat_message_decode() {
let mut cursor = Cursor::new(
include_bytes!("../test/packet/game/server_bound_chat_message.dat").to_vec(),
);
let chat_message = ServerBoundChatMessage::decode(&mut cursor).unwrap();
assert_eq!(chat_message.message, "hello server!");
}
#[test]
fn test_server_bound_chat_message_encode_invalid_length() {
let chat_message = ServerBoundChatMessage {
message: "abc".repeat(100),
};
let mut vec = Vec::new();
let encode_error = chat_message
.encode(&mut vec)
.err()
.expect("Expected error `StringTooLong` because message has invalid length");
match encode_error {
EncodeError::StringTooLong { length, max_length } => {
assert_eq!(length, 300);
assert_eq!(max_length, 256);
}
_ => panic!("Expected `StringTooLong` but got `{:?}`", encode_error),
}
}
#[test]
fn test_server_bound_chat_message_decode_invalid_length() {
let message = "abc".repeat(100);
let mut vec = Vec::new();
vec.write_string(&message, STRING_MAX_LENGTH).unwrap();
let mut cursor = Cursor::new(vec);
let decode_error = ServerBoundChatMessage::decode(&mut cursor)
.err()
.expect("Expected error `StringTooLong` because message has invalid length");
match decode_error {
DecodeError::StringTooLong { length, max_length } => {
assert_eq!(length, 300);
assert_eq!(max_length, 256);
}
_ => panic!("Expected `StringTooLong` but got `{:?}`", decode_error),
}
}
#[test]
fn test_client_bound_chat_message_encode() {
let chat_message = ClientBoundChatMessage {
message: Message::new(Payload::text("hello client!")),
position: MessagePosition::System,
};
let mut vec = Vec::new();
chat_message.encode(&mut vec).unwrap();
assert_eq!(
vec,
include_bytes!("../test/packet/game/client_bound_chat_message.dat").to_vec()
);
}
#[test]
fn test_client_bound_chat_message_decode() {
let mut cursor = Cursor::new(
include_bytes!("../test/packet/game/client_bound_chat_message.dat").to_vec(),
);
let chat_message = ClientBoundChatMessage::decode(&mut cursor).unwrap();
assert_eq!(
chat_message.message,
Message::new(Payload::text("hello client!"))
);
assert_eq!(chat_message.position, MessagePosition::System);
}
#[test]
fn test_server_bound_keep_alive_encode() {
let keep_alive = ServerBoundKeepAlive { id: 31122019 };
let mut vec = Vec::new();
keep_alive.encode(&mut vec).unwrap();
assert_eq!(
vec,
include_bytes!("../test/packet/game/server_bound_keep_alive.dat").to_vec()
);
}
#[test]
fn test_server_bound_keep_alive_decode() {
let mut cursor =
Cursor::new(include_bytes!("../test/packet/game/server_bound_keep_alive.dat").to_vec());
let keep_alive = ServerBoundKeepAlive::decode(&mut cursor).unwrap();
assert_eq!(keep_alive.id, 31122019);
}
#[test]
fn test_client_bound_keep_alive_encode() {
let keep_alive = ClientBoundKeepAlive { id: 240714 };
let mut vec = Vec::new();
keep_alive.encode(&mut vec).unwrap();
assert_eq!(
vec,
include_bytes!("../test/packet/game/client_bound_keep_alive.dat").to_vec()
);
}
#[test]
fn test_client_bound_keep_alive_decode() {
let mut cursor =
Cursor::new(include_bytes!("../test/packet/game/client_bound_keep_alive.dat").to_vec());
let keep_alive = ClientBoundKeepAlive::decode(&mut cursor).unwrap();
assert_eq!(keep_alive.id, 240714);
}
#[test]
fn test_join_game_encode() {
let join_game = JoinGame {
entity_id: 27,
game_mode: GameMode::Spectator,
dimension: 23,
max_players: 100,
level_type: String::from("default"),
view_distance: 10,
reduced_debug_info: true,
};
let mut vec = Vec::new();
join_game.encode(&mut vec).unwrap();
assert_eq!(
vec,
include_bytes!("../test/packet/game/join_game.dat").to_vec()
);
}
#[test]
fn test_join_game_decode() {
let mut cursor = Cursor::new(include_bytes!("../test/packet/game/join_game.dat").to_vec());
let join_game = JoinGame::decode(&mut cursor).unwrap();
assert_eq!(join_game.entity_id, 27);
assert_eq!(join_game.game_mode, GameMode::Spectator);
assert_eq!(join_game.dimension, 23);
assert_eq!(join_game.max_players, 100);
assert_eq!(join_game.level_type, String::from("default"));
assert_eq!(join_game.view_distance, 10);
assert!(join_game.reduced_debug_info);
}
#[test]
fn test_chunk_data_encode() {
let chunk_data = ChunkData {
x: -2,
z: 5,
full: true,
primary_mask: 65535,
heights: CompoundTag::named("HeightMaps"),
data: vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
tiles: vec![CompoundTag::named("TileEntity")],
};
let mut vec = Vec::new();
chunk_data.encode(&mut vec).unwrap();
assert_eq!(
vec,
include_bytes!("../test/packet/game/chunk_data.dat").to_vec()
);
}
#[test]
fn test_chunk_data_decode() {
let mut cursor = Cursor::new(include_bytes!("../test/packet/game/chunk_data.dat").to_vec());
let chunk_data = ChunkData::decode(&mut cursor).unwrap();
assert_eq!(chunk_data.x, -2);
assert_eq!(chunk_data.z, 5);
assert!(chunk_data.full);
assert_eq!(chunk_data.heights.name, Some(String::from("HeightMaps")));
assert_eq!(chunk_data.data, vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
assert_eq!(chunk_data.primary_mask, 65535);
assert_eq!(chunk_data.tiles[0].name, Some(String::from("TileEntity")));
}
#[test]
fn test_game_disconnect_encode() {
let game_disconnect = GameDisconnect {
reason: Message::new(Payload::text("Message")),
};
let mut vec = Vec::new();
game_disconnect.encode(&mut vec).unwrap();
assert_eq!(
vec,
include_bytes!("../test/packet/game/game_disconnect.dat").to_vec()
);
}
#[test]
fn test_game_disconnect_decode() {
let mut cursor =
Cursor::new(include_bytes!("../test/packet/game/game_disconnect.dat").to_vec());
let game_disconnect = GameDisconnect::decode(&mut cursor).unwrap();
assert_eq!(
game_disconnect.reason,
Message::new(Payload::text("Message"))
);
}
}

View File

@ -1,25 +1,20 @@
//! This crate implements Minecraft protocol.
//!
//! Information about protocol can be found at https://wiki.vg/Protocol.
use io::Error as IoError;
use std::io;
use std::io::{Cursor, Read, Write};
use std::string::FromUtf8Error;
use std::io::{Read, Write};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use serde_json::error::Error as JsonError;
use uuid::parser::ParseError as UuidParseError;
use crate::chat::Message;
use nbt::decode::TagDecodeError;
use nbt::CompoundTag;
use num_traits::{FromPrimitive, ToPrimitive};
use uuid::Uuid;
pub mod chat;
pub mod game;
pub mod login;
pub mod status;
use data::chat::Message;
use crate::error::{DecodeError, EncodeError};
pub mod data;
pub mod error;
pub mod packet;
/// Current supported protocol version.
pub const PROTOCOL_VERSION: u32 = 498;
@ -27,107 +22,6 @@ pub const PROTOCOL_VERSION: u32 = 498;
const STRING_MAX_LENGTH: u16 = 32_768;
const HYPHENATED_UUID_LENGTH: u16 = 36;
/// Possible errors while encoding packet.
#[derive(Debug)]
pub enum EncodeError {
/// String length can't be more than provided value.
StringTooLong {
/// String length.
length: usize,
/// Max string length.
max_length: u16,
},
IOError {
io_error: IoError,
},
JsonError {
json_error: JsonError,
},
}
impl From<IoError> for EncodeError {
fn from(io_error: IoError) -> Self {
EncodeError::IOError { io_error }
}
}
impl From<JsonError> for EncodeError {
fn from(json_error: JsonError) -> Self {
EncodeError::JsonError { json_error }
}
}
/// Possible errors while decoding packet.
#[derive(Debug)]
pub enum DecodeError {
/// Packet was not recognized. Invalid data or wrong protocol version.
UnknownPacketType {
type_id: u8,
},
/// String length can't be more than provided value.
StringTooLong {
/// String length.
length: usize,
/// Max string length.
max_length: u16,
},
IOError {
io_error: IoError,
},
JsonError {
json_error: JsonError,
},
/// Byte array was not recognized as valid UTF-8 string.
Utf8Error {
utf8_error: FromUtf8Error,
},
/// Boolean are parsed from byte. Valid byte value are 0 or 1.
NonBoolValue,
UuidParseError {
uuid_parse_error: UuidParseError,
},
// Type id was not parsed as valid enum value.
UnknownEnumType {
type_id: u8,
},
TagDecodeError {
tag_decode_error: TagDecodeError,
},
VarIntTooLong {
max_bytes: usize,
},
}
impl From<IoError> for DecodeError {
fn from(io_error: IoError) -> Self {
DecodeError::IOError { io_error }
}
}
impl From<JsonError> for DecodeError {
fn from(json_error: JsonError) -> Self {
DecodeError::JsonError { json_error }
}
}
impl From<FromUtf8Error> for DecodeError {
fn from(utf8_error: FromUtf8Error) -> Self {
DecodeError::Utf8Error { utf8_error }
}
}
impl From<UuidParseError> for DecodeError {
fn from(uuid_parse_error: UuidParseError) -> Self {
DecodeError::UuidParseError { uuid_parse_error }
}
}
impl From<TagDecodeError> for DecodeError {
fn from(tag_decode_error: TagDecodeError) -> Self {
DecodeError::TagDecodeError { tag_decode_error }
}
}
trait Encoder {
fn encode<W: Write>(&self, writer: &mut W) -> Result<(), EncodeError>;
}
@ -546,9 +440,10 @@ macro_rules! impl_json_encoder_decoder (
);
mod var_int {
use std::io::{Read, Write};
use crate::{DecodeError, EncodeError};
use crate::{DecoderReadExt, EncoderWriteExt};
use std::io::{Read, Write};
pub fn encode<W: Write>(value: &i32, writer: &mut W) -> Result<(), EncodeError> {
writer.write_var_i32(*value)?;
@ -562,9 +457,10 @@ mod var_int {
}
mod var_long {
use std::io::{Read, Write};
use crate::{DecodeError, EncodeError};
use crate::{DecoderReadExt, EncoderWriteExt};
use std::io::{Read, Write};
pub fn encode<W: Write>(value: &i64, writer: &mut W) -> Result<(), EncodeError> {
writer.write_var_i64(*value)?;
@ -578,9 +474,10 @@ mod var_long {
}
mod rest {
use crate::{DecodeError, EncodeError};
use std::io::{Read, Write};
use crate::{DecodeError, EncodeError};
pub fn encode<W: Write>(value: &[u8], writer: &mut W) -> Result<(), EncodeError> {
writer.write_all(value)?;
@ -596,11 +493,13 @@ mod rest {
}
mod uuid_hyp_str {
use std::io::{Read, Write};
use uuid::Uuid;
use crate::{
DecodeError, DecoderReadExt, EncodeError, EncoderWriteExt, HYPHENATED_UUID_LENGTH,
};
use std::io::{Read, Write};
use uuid::Uuid;
pub fn encode<W: Write>(value: &Uuid, writer: &mut W) -> Result<(), EncodeError> {
let uuid_hyphenated_string = value.to_hyphenated().to_string();

View File

@ -1,479 +0,0 @@
use crate::chat::Message;
use crate::DecodeError;
use crate::Decoder;
use std::io::Read;
use uuid::Uuid;
use minecraft_protocol_derive::Packet;
pub enum LoginServerBoundPacket {
LoginStart(LoginStart),
EncryptionResponse(EncryptionResponse),
LoginPluginResponse(LoginPluginResponse),
}
pub enum LoginClientBoundPacket {
LoginDisconnect(LoginDisconnect),
EncryptionRequest(EncryptionRequest),
LoginSuccess(LoginSuccess),
SetCompression(SetCompression),
LoginPluginRequest(LoginPluginRequest),
}
impl LoginServerBoundPacket {
pub fn get_type_id(&self) -> u8 {
match self {
LoginServerBoundPacket::LoginStart(_) => 0x00,
LoginServerBoundPacket::EncryptionResponse(_) => 0x01,
LoginServerBoundPacket::LoginPluginResponse(_) => 0x02,
}
}
pub fn decode<R: Read>(type_id: u8, reader: &mut R) -> Result<Self, DecodeError> {
match type_id {
0x00 => {
let login_start = LoginStart::decode(reader)?;
Ok(LoginServerBoundPacket::LoginStart(login_start))
}
0x01 => {
let encryption_response = EncryptionResponse::decode(reader)?;
Ok(LoginServerBoundPacket::EncryptionResponse(
encryption_response,
))
}
0x02 => {
let login_plugin_response = LoginPluginResponse::decode(reader)?;
Ok(LoginServerBoundPacket::LoginPluginResponse(
login_plugin_response,
))
}
_ => Err(DecodeError::UnknownPacketType { type_id }),
}
}
}
impl LoginClientBoundPacket {
pub fn get_type_id(&self) -> u8 {
match self {
LoginClientBoundPacket::LoginDisconnect(_) => 0x00,
LoginClientBoundPacket::EncryptionRequest(_) => 0x01,
LoginClientBoundPacket::LoginSuccess(_) => 0x02,
LoginClientBoundPacket::SetCompression(_) => 0x03,
LoginClientBoundPacket::LoginPluginRequest(_) => 0x04,
}
}
pub fn decode<R: Read>(type_id: u8, reader: &mut R) -> Result<Self, DecodeError> {
match type_id {
0x00 => {
let login_disconnect = LoginDisconnect::decode(reader)?;
Ok(LoginClientBoundPacket::LoginDisconnect(login_disconnect))
}
0x01 => {
let encryption_request = EncryptionRequest::decode(reader)?;
Ok(LoginClientBoundPacket::EncryptionRequest(
encryption_request,
))
}
0x02 => {
let login_success = LoginSuccess::decode(reader)?;
Ok(LoginClientBoundPacket::LoginSuccess(login_success))
}
0x03 => {
let set_compression = SetCompression::decode(reader)?;
Ok(LoginClientBoundPacket::SetCompression(set_compression))
}
0x04 => {
let login_plugin_request = LoginPluginRequest::decode(reader)?;
Ok(LoginClientBoundPacket::LoginPluginRequest(
login_plugin_request,
))
}
_ => Err(DecodeError::UnknownPacketType { type_id }),
}
}
}
#[derive(Packet, Debug)]
pub struct LoginStart {
pub name: String,
}
impl LoginStart {
pub fn new(name: String) -> LoginServerBoundPacket {
let login_start = LoginStart { name };
LoginServerBoundPacket::LoginStart(login_start)
}
}
#[derive(Packet, Debug)]
pub struct EncryptionResponse {
pub shared_secret: Vec<u8>,
pub verify_token: Vec<u8>,
}
impl EncryptionResponse {
pub fn new(shared_secret: Vec<u8>, verify_token: Vec<u8>) -> LoginServerBoundPacket {
let encryption_response = EncryptionResponse {
shared_secret,
verify_token,
};
LoginServerBoundPacket::EncryptionResponse(encryption_response)
}
}
#[derive(Packet, Debug)]
pub struct LoginPluginResponse {
#[packet(with = "var_int")]
pub message_id: i32,
pub successful: bool,
#[packet(with = "rest")]
pub data: Vec<u8>,
}
impl LoginPluginResponse {
pub fn new(message_id: i32, successful: bool, data: Vec<u8>) -> LoginServerBoundPacket {
let login_plugin_response = LoginPluginResponse {
message_id,
successful,
data,
};
LoginServerBoundPacket::LoginPluginResponse(login_plugin_response)
}
}
#[derive(Packet, Debug)]
pub struct LoginDisconnect {
pub reason: Message,
}
impl LoginDisconnect {
pub fn new(reason: Message) -> LoginClientBoundPacket {
let login_disconnect = LoginDisconnect { reason };
LoginClientBoundPacket::LoginDisconnect(login_disconnect)
}
}
#[derive(Packet, Debug)]
pub struct EncryptionRequest {
#[packet(max_length = 20)]
pub server_id: String,
pub public_key: Vec<u8>,
pub verify_token: Vec<u8>,
}
impl EncryptionRequest {
pub fn new(
server_id: String,
public_key: Vec<u8>,
verify_token: Vec<u8>,
) -> LoginClientBoundPacket {
let encryption_request = EncryptionRequest {
server_id,
public_key,
verify_token,
};
LoginClientBoundPacket::EncryptionRequest(encryption_request)
}
}
#[derive(Packet, Debug)]
pub struct LoginSuccess {
#[packet(with = "uuid_hyp_str")]
pub uuid: Uuid,
#[packet(max_length = 16)]
pub username: String,
}
impl LoginSuccess {
pub fn new(uuid: Uuid, username: String) -> LoginClientBoundPacket {
let login_success = LoginSuccess { uuid, username };
LoginClientBoundPacket::LoginSuccess(login_success)
}
}
#[derive(Packet, Debug)]
pub struct SetCompression {
#[packet(with = "var_int")]
pub threshold: i32,
}
impl SetCompression {
pub fn new(threshold: i32) -> LoginClientBoundPacket {
let set_compression = SetCompression { threshold };
LoginClientBoundPacket::SetCompression(set_compression)
}
}
#[derive(Packet, Debug)]
pub struct LoginPluginRequest {
#[packet(with = "var_int")]
pub message_id: i32,
pub channel: String,
#[packet(with = "rest")]
pub data: Vec<u8>,
}
impl LoginPluginRequest {
pub fn new(message_id: i32, channel: String, data: Vec<u8>) -> LoginClientBoundPacket {
let login_plugin_request = LoginPluginRequest {
message_id,
channel,
data,
};
LoginClientBoundPacket::LoginPluginRequest(login_plugin_request)
}
}
#[cfg(test)]
mod tests {
use crate::chat::{Message, Payload};
use crate::login::{EncryptionRequest, LoginDisconnect, LoginPluginRequest, SetCompression};
use crate::login::{EncryptionResponse, LoginPluginResponse};
use crate::login::{LoginStart, LoginSuccess};
use crate::Decoder;
use crate::Encoder;
use std::io::Cursor;
use uuid::Uuid;
#[test]
fn test_login_start_packet_encode() {
let login_start = LoginStart {
name: String::from("Username"),
};
let mut vec = Vec::new();
login_start.encode(&mut vec).unwrap();
assert_eq!(
vec,
include_bytes!("../test/packet/login/login_start.dat").to_vec()
);
}
#[test]
fn test_login_start_packet_decode() {
let mut cursor =
Cursor::new(include_bytes!("../test/packet/login/login_start.dat").to_vec());
let login_start = LoginStart::decode(&mut cursor).unwrap();
assert_eq!(login_start.name, String::from("Username"));
}
#[test]
fn test_encryption_response_encode() {
let encryption_response = EncryptionResponse {
shared_secret: vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
verify_token: vec![1, 2, 3, 4],
};
let mut vec = Vec::new();
encryption_response.encode(&mut vec).unwrap();
assert_eq!(
vec,
include_bytes!("../test/packet/login/encryption_response.dat").to_vec()
);
}
#[test]
fn test_encryption_response_decode() {
let mut cursor =
Cursor::new(include_bytes!("../test/packet/login/encryption_response.dat").to_vec());
let encryption_response = EncryptionResponse::decode(&mut cursor).unwrap();
assert_eq!(
encryption_response.shared_secret,
vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
);
assert_eq!(encryption_response.verify_token, vec![1, 2, 3, 4]);
}
#[test]
fn test_login_plugin_response_encode() {
let login_plugin_response = LoginPluginResponse {
message_id: 55,
successful: true,
data: vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
};
let mut vec = Vec::new();
login_plugin_response.encode(&mut vec).unwrap();
assert_eq!(
vec,
include_bytes!("../test/packet/login/login_plugin_response.dat").to_vec()
);
}
#[test]
fn test_login_plugin_response_decode() {
let mut cursor =
Cursor::new(include_bytes!("../test/packet/login/login_plugin_response.dat").to_vec());
let login_plugin_response = LoginPluginResponse::decode(&mut cursor).unwrap();
assert_eq!(login_plugin_response.message_id, 55);
assert!(login_plugin_response.successful);
assert_eq!(
login_plugin_response.data,
vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
);
}
#[test]
fn test_login_disconnect_encode() {
let login_disconnect = LoginDisconnect {
reason: Message::new(Payload::text("Message")),
};
let mut vec = Vec::new();
login_disconnect.encode(&mut vec).unwrap();
assert_eq!(
vec,
include_bytes!("../test/packet/login/login_disconnect.dat").to_vec()
);
}
#[test]
fn test_login_disconnect_decode() {
let mut cursor =
Cursor::new(include_bytes!("../test/packet/login/login_disconnect.dat").to_vec());
let login_disconnect = LoginDisconnect::decode(&mut cursor).unwrap();
assert_eq!(
login_disconnect.reason,
Message::new(Payload::text("Message"))
);
}
#[test]
fn test_encryption_request_encode() {
let encryption_request = EncryptionRequest {
server_id: String::from("ServerID"),
public_key: vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
verify_token: vec![1, 2, 3, 4],
};
let mut vec = Vec::new();
encryption_request.encode(&mut vec).unwrap();
assert_eq!(
vec,
include_bytes!("../test/packet/login/encryption_request.dat").to_vec()
);
}
#[test]
fn test_encryption_request_decode() {
let mut cursor =
Cursor::new(include_bytes!("../test/packet/login/encryption_request.dat").to_vec());
let encryption_request = EncryptionRequest::decode(&mut cursor).unwrap();
assert_eq!(encryption_request.server_id, String::from("ServerID"));
assert_eq!(
encryption_request.public_key,
vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
);
assert_eq!(encryption_request.verify_token, vec![1, 2, 3, 4]);
}
#[test]
fn test_login_success_encode() {
let login_success = LoginSuccess {
uuid: Uuid::parse_str("35ee313b-d89a-41b8-b25e-d32e8aff0389").unwrap(),
username: String::from("Username"),
};
let mut vec = Vec::new();
login_success.encode(&mut vec).unwrap();
assert_eq!(
vec,
include_bytes!("../test/packet/login/login_success.dat").to_vec()
);
}
#[test]
fn test_login_success_decode() {
let mut cursor =
Cursor::new(include_bytes!("../test/packet/login/login_success.dat").to_vec());
let login_success = LoginSuccess::decode(&mut cursor).unwrap();
assert_eq!(login_success.username, String::from("Username"));
assert_eq!(
login_success.uuid,
Uuid::parse_str("35ee313b-d89a-41b8-b25e-d32e8aff0389").unwrap()
);
}
#[test]
fn test_set_compression_encode() {
let set_compression = SetCompression { threshold: 1 };
let mut vec = Vec::new();
set_compression.encode(&mut vec).unwrap();
assert_eq!(
vec,
include_bytes!("../test/packet/login/login_set_compression.dat").to_vec()
);
}
#[test]
fn test_set_compression_decode() {
let mut cursor =
Cursor::new(include_bytes!("../test/packet/login/login_set_compression.dat").to_vec());
let set_compression = SetCompression::decode(&mut cursor).unwrap();
assert_eq!(set_compression.threshold, 1);
}
#[test]
fn test_login_plugin_request_encode() {
let login_plugin_request = LoginPluginRequest {
message_id: 55,
channel: String::from("Channel"),
data: vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
};
let mut vec = Vec::new();
login_plugin_request.encode(&mut vec).unwrap();
assert_eq!(
vec,
include_bytes!("../test/packet/login/login_plugin_request.dat").to_vec()
);
}
#[test]
fn test_login_plugin_request_decode() {
let mut cursor =
Cursor::new(include_bytes!("../test/packet/login/login_plugin_request.dat").to_vec());
let login_plugin_request = LoginPluginRequest::decode(&mut cursor).unwrap();
assert_eq!(login_plugin_request.message_id, 55);
assert_eq!(login_plugin_request.channel, String::from("Channel"));
assert_eq!(
login_plugin_request.data,
vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
);
}
}

140
protocol/src/packet/game.rs Normal file
View File

@ -0,0 +1,140 @@
use crate::data::chat::Message;
use crate::data::game::{GameMode, MessagePosition};
use crate::DecodeError;
use crate::Decoder;
use minecraft_protocol_derive::Packet;
use nbt::CompoundTag;
use std::io::Read;
pub enum GameServerBoundPacket {
ServerBoundChatMessage(ServerBoundChatMessage),
ServerBoundKeepAlive(ServerBoundKeepAlive),
}
pub enum GameClientBoundPacket {
ClientBoundChatMessage(ClientBoundChatMessage),
JoinGame(JoinGame),
ClientBoundKeepAlive(ClientBoundKeepAlive),
ChunkData(ChunkData),
GameDisconnect(GameDisconnect),
}
impl GameServerBoundPacket {
pub fn get_type_id(&self) -> u8 {
match self {
GameServerBoundPacket::ServerBoundChatMessage(_) => 0x03,
GameServerBoundPacket::ServerBoundKeepAlive(_) => 0x0F,
}
}
pub fn decode<R: Read>(type_id: u8, reader: &mut R) -> Result<Self, DecodeError> {
match type_id {
0x03 => {
let chat_message = ServerBoundChatMessage::decode(reader)?;
Ok(GameServerBoundPacket::ServerBoundChatMessage(chat_message))
}
0x0F => {
let keep_alive = ServerBoundKeepAlive::decode(reader)?;
Ok(GameServerBoundPacket::ServerBoundKeepAlive(keep_alive))
}
_ => Err(DecodeError::UnknownPacketType { type_id }),
}
}
}
impl GameClientBoundPacket {
pub fn get_type_id(&self) -> u8 {
match self {
GameClientBoundPacket::ClientBoundChatMessage(_) => 0x0E,
GameClientBoundPacket::GameDisconnect(_) => 0x1A,
GameClientBoundPacket::ClientBoundKeepAlive(_) => 0x20,
GameClientBoundPacket::ChunkData(_) => 0x21,
GameClientBoundPacket::JoinGame(_) => 0x25,
}
}
pub fn decode<R: Read>(type_id: u8, reader: &mut R) -> Result<Self, DecodeError> {
match type_id {
0x0E => {
let chat_message = ClientBoundChatMessage::decode(reader)?;
Ok(GameClientBoundPacket::ClientBoundChatMessage(chat_message))
}
0x1A => {
let game_disconnect = GameDisconnect::decode(reader)?;
Ok(GameClientBoundPacket::GameDisconnect(game_disconnect))
}
0x20 => {
let keep_alive = ClientBoundKeepAlive::decode(reader)?;
Ok(GameClientBoundPacket::ClientBoundKeepAlive(keep_alive))
}
0x21 => {
let chunk_data = ChunkData::decode(reader)?;
Ok(GameClientBoundPacket::ChunkData(chunk_data))
}
0x25 => {
let join_game = JoinGame::decode(reader)?;
Ok(GameClientBoundPacket::JoinGame(join_game))
}
_ => Err(DecodeError::UnknownPacketType { type_id }),
}
}
}
#[derive(Packet, Debug)]
pub struct ServerBoundChatMessage {
#[packet(max_length = 256)]
pub message: String,
}
#[derive(Packet, Debug)]
pub struct ClientBoundChatMessage {
pub message: Message,
pub position: MessagePosition,
}
#[derive(Packet, Debug)]
pub struct JoinGame {
pub entity_id: u32,
pub game_mode: GameMode,
pub dimension: i32,
pub max_players: u8,
#[packet(max_length = 16)]
pub level_type: String,
#[packet(with = "var_int")]
pub view_distance: i32,
pub reduced_debug_info: bool,
}
#[derive(Packet)]
pub struct ServerBoundKeepAlive {
pub id: u64,
}
#[derive(Packet)]
pub struct ClientBoundKeepAlive {
pub id: u64,
}
#[derive(Packet, Debug)]
pub struct ChunkData {
pub x: i32,
pub z: i32,
pub full: bool,
#[packet(with = "var_int")]
pub primary_mask: i32,
pub heights: CompoundTag,
pub data: Vec<u8>,
pub tiles: Vec<CompoundTag>,
}
#[derive(Packet, Debug)]
pub struct GameDisconnect {
pub reason: Message,
}

View File

@ -0,0 +1,159 @@
use crate::data::chat::Message;
use crate::DecodeError;
use crate::Decoder;
use std::io::Read;
use uuid::Uuid;
use minecraft_protocol_derive::Packet;
pub enum LoginServerBoundPacket {
LoginStart(LoginStart),
EncryptionResponse(EncryptionResponse),
LoginPluginResponse(LoginPluginResponse),
}
pub enum LoginClientBoundPacket {
LoginDisconnect(LoginDisconnect),
EncryptionRequest(EncryptionRequest),
LoginSuccess(LoginSuccess),
SetCompression(SetCompression),
LoginPluginRequest(LoginPluginRequest),
}
impl LoginServerBoundPacket {
pub fn get_type_id(&self) -> u8 {
match self {
LoginServerBoundPacket::LoginStart(_) => 0x00,
LoginServerBoundPacket::EncryptionResponse(_) => 0x01,
LoginServerBoundPacket::LoginPluginResponse(_) => 0x02,
}
}
pub fn decode<R: Read>(type_id: u8, reader: &mut R) -> Result<Self, DecodeError> {
match type_id {
0x00 => {
let login_start = LoginStart::decode(reader)?;
Ok(LoginServerBoundPacket::LoginStart(login_start))
}
0x01 => {
let encryption_response = EncryptionResponse::decode(reader)?;
Ok(LoginServerBoundPacket::EncryptionResponse(
encryption_response,
))
}
0x02 => {
let login_plugin_response = LoginPluginResponse::decode(reader)?;
Ok(LoginServerBoundPacket::LoginPluginResponse(
login_plugin_response,
))
}
_ => Err(DecodeError::UnknownPacketType { type_id }),
}
}
}
impl LoginClientBoundPacket {
pub fn get_type_id(&self) -> u8 {
match self {
LoginClientBoundPacket::LoginDisconnect(_) => 0x00,
LoginClientBoundPacket::EncryptionRequest(_) => 0x01,
LoginClientBoundPacket::LoginSuccess(_) => 0x02,
LoginClientBoundPacket::SetCompression(_) => 0x03,
LoginClientBoundPacket::LoginPluginRequest(_) => 0x04,
}
}
pub fn decode<R: Read>(type_id: u8, reader: &mut R) -> Result<Self, DecodeError> {
match type_id {
0x00 => {
let login_disconnect = LoginDisconnect::decode(reader)?;
Ok(LoginClientBoundPacket::LoginDisconnect(login_disconnect))
}
0x01 => {
let encryption_request = EncryptionRequest::decode(reader)?;
Ok(LoginClientBoundPacket::EncryptionRequest(
encryption_request,
))
}
0x02 => {
let login_success = LoginSuccess::decode(reader)?;
Ok(LoginClientBoundPacket::LoginSuccess(login_success))
}
0x03 => {
let set_compression = SetCompression::decode(reader)?;
Ok(LoginClientBoundPacket::SetCompression(set_compression))
}
0x04 => {
let login_plugin_request = LoginPluginRequest::decode(reader)?;
Ok(LoginClientBoundPacket::LoginPluginRequest(
login_plugin_request,
))
}
_ => Err(DecodeError::UnknownPacketType { type_id }),
}
}
}
#[derive(Packet, Debug)]
pub struct LoginStart {
pub name: String,
}
#[derive(Packet, Debug)]
pub struct EncryptionResponse {
pub shared_secret: Vec<u8>,
pub verify_token: Vec<u8>,
}
#[derive(Packet, Debug)]
pub struct LoginPluginResponse {
#[packet(with = "var_int")]
pub message_id: i32,
pub successful: bool,
#[packet(with = "rest")]
pub data: Vec<u8>,
}
#[derive(Packet, Debug)]
pub struct LoginDisconnect {
pub reason: Message,
}
#[derive(Packet, Debug)]
pub struct EncryptionRequest {
#[packet(max_length = 20)]
pub server_id: String,
pub public_key: Vec<u8>,
pub verify_token: Vec<u8>,
}
#[derive(Packet, Debug)]
pub struct LoginSuccess {
#[packet(with = "uuid_hyp_str")]
pub uuid: Uuid,
#[packet(max_length = 16)]
pub username: String,
}
#[derive(Packet, Debug)]
pub struct SetCompression {
#[packet(with = "var_int")]
pub threshold: i32,
}
#[derive(Packet, Debug)]
pub struct LoginPluginRequest {
#[packet(with = "var_int")]
pub message_id: i32,
pub channel: String,
#[packet(with = "rest")]
pub data: Vec<u8>,
}

View File

@ -0,0 +1,3 @@
pub mod game;
pub mod login;
pub mod status;

View File

@ -0,0 +1,60 @@
use crate::data::status::ServerStatus;
use crate::DecodeError;
use crate::Decoder;
use minecraft_protocol_derive::Packet;
use std::io::Read;
pub enum StatusServerBoundPacket {
StatusRequest,
PingRequest(PingRequest),
}
pub enum StatusClientBoundPacket {
StatusResponse(StatusResponse),
PingResponse(PingResponse),
}
impl StatusServerBoundPacket {
pub fn get_type_id(&self) -> u8 {
match self {
StatusServerBoundPacket::StatusRequest => 0x00,
StatusServerBoundPacket::PingRequest(_) => 0x01,
}
}
pub fn decode<R: Read>(type_id: u8, reader: &mut R) -> Result<Self, DecodeError> {
match type_id {
0x00 => Ok(StatusServerBoundPacket::StatusRequest),
0x01 => {
let ping_request = PingRequest::decode(reader)?;
Ok(StatusServerBoundPacket::PingRequest(ping_request))
}
_ => Err(DecodeError::UnknownPacketType { type_id }),
}
}
}
impl StatusClientBoundPacket {
pub fn get_type_id(&self) -> u8 {
match self {
StatusClientBoundPacket::StatusResponse(_) => 0x00,
StatusClientBoundPacket::PingResponse(_) => 0x01,
}
}
}
#[derive(Packet, Debug)]
pub struct PingRequest {
pub time: u64,
}
#[derive(Packet, Debug)]
pub struct PingResponse {
pub time: u64,
}
#[derive(Packet, Debug)]
pub struct StatusResponse {
pub server_status: ServerStatus,
}

View File

@ -1,235 +0,0 @@
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::chat::Message;
use crate::impl_json_encoder_decoder;
use crate::DecodeError;
use crate::Decoder;
use minecraft_protocol_derive::Packet;
use std::io::Read;
pub enum StatusServerBoundPacket {
StatusRequest,
PingRequest(PingRequest),
}
pub enum StatusClientBoundPacket {
StatusResponse(StatusResponse),
PingResponse(PingResponse),
}
impl StatusServerBoundPacket {
pub fn get_type_id(&self) -> u8 {
match self {
StatusServerBoundPacket::StatusRequest => 0x00,
StatusServerBoundPacket::PingRequest(_) => 0x01,
}
}
pub fn decode<R: Read>(type_id: u8, reader: &mut R) -> Result<Self, DecodeError> {
match type_id {
0x00 => Ok(StatusServerBoundPacket::StatusRequest),
0x01 => {
let ping_request = PingRequest::decode(reader)?;
Ok(StatusServerBoundPacket::PingRequest(ping_request))
}
_ => Err(DecodeError::UnknownPacketType { type_id }),
}
}
}
impl StatusClientBoundPacket {
pub fn get_type_id(&self) -> u8 {
match self {
StatusClientBoundPacket::StatusResponse(_) => 0x00,
StatusClientBoundPacket::PingResponse(_) => 0x01,
}
}
}
#[derive(Packet, Debug)]
pub struct PingRequest {
pub time: u64,
}
impl PingRequest {
pub fn new(time: u64) -> StatusServerBoundPacket {
let ping_request = PingRequest { time };
StatusServerBoundPacket::PingRequest(ping_request)
}
}
#[derive(Packet, Debug)]
pub struct PingResponse {
pub time: u64,
}
impl PingResponse {
pub fn new(time: u64) -> StatusClientBoundPacket {
let ping_response = PingResponse { time };
StatusClientBoundPacket::PingResponse(ping_response)
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ServerStatus {
pub version: ServerVersion,
pub players: OnlinePlayers,
pub description: Message,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ServerVersion {
pub name: String,
pub protocol: u32,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct OnlinePlayers {
pub max: u32,
pub online: u32,
pub sample: Vec<OnlinePlayer>,
}
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
pub struct OnlinePlayer {
pub name: String,
pub id: Uuid,
}
#[derive(Packet, Debug)]
pub struct StatusResponse {
pub server_status: ServerStatus,
}
impl_json_encoder_decoder!(ServerStatus);
impl StatusResponse {
pub fn new(server_status: ServerStatus) -> StatusClientBoundPacket {
let status_response = StatusResponse { server_status };
StatusClientBoundPacket::StatusResponse(status_response)
}
}
#[cfg(test)]
mod tests {
use crate::chat::{Message, Payload};
use crate::status::{
OnlinePlayer, OnlinePlayers, PingRequest, PingResponse, ServerStatus, ServerVersion,
StatusResponse,
};
use crate::Decoder;
use crate::Encoder;
use std::io::Cursor;
use uuid::Uuid;
#[test]
fn test_ping_request_encode() {
let ping_request = PingRequest {
time: 1577735845610,
};
let mut vec = Vec::new();
ping_request.encode(&mut vec).unwrap();
assert_eq!(
vec,
include_bytes!("../test/packet/status/ping_request.dat").to_vec()
);
}
#[test]
fn test_status_ping_request_decode() {
let mut cursor =
Cursor::new(include_bytes!("../test/packet/status/ping_request.dat").to_vec());
let ping_request = PingRequest::decode(&mut cursor).unwrap();
assert_eq!(ping_request.time, 1577735845610);
}
#[test]
fn test_ping_response_encode() {
let ping_response = PingResponse {
time: 1577735845610,
};
let mut vec = Vec::new();
ping_response.encode(&mut vec).unwrap();
assert_eq!(
vec,
include_bytes!("../test/packet/status/ping_response.dat").to_vec()
);
}
#[test]
fn test_status_ping_response_decode() {
let mut cursor =
Cursor::new(include_bytes!("../test/packet/status/ping_response.dat").to_vec());
let ping_response = PingResponse::decode(&mut cursor).unwrap();
assert_eq!(ping_response.time, 1577735845610);
}
#[test]
fn test_status_response_encode() {
let version = ServerVersion {
name: String::from("1.15.1"),
protocol: 575,
};
let player = OnlinePlayer {
id: Uuid::parse_str("2a1e1912-7103-4add-80fc-91ebc346cbce").unwrap(),
name: String::from("Username"),
};
let players = OnlinePlayers {
online: 10,
max: 100,
sample: vec![player],
};
let server_status = ServerStatus {
version,
description: Message::new(Payload::text("Description")),
players,
};
let status_response = StatusResponse { server_status };
let mut vec = Vec::new();
status_response.encode(&mut vec).unwrap();
assert_eq!(
vec,
include_bytes!("../test/packet/status/status_response.dat").to_vec()
);
}
#[test]
fn test_status_response_decode() {
let mut cursor =
Cursor::new(include_bytes!("../test/packet/status/status_response.dat").to_vec());
let status_response = StatusResponse::decode(&mut cursor).unwrap();
let server_status = status_response.server_status;
let player = OnlinePlayer {
id: Uuid::parse_str("2a1e1912-7103-4add-80fc-91ebc346cbce").unwrap(),
name: String::from("Username"),
};
assert_eq!(server_status.version.name, String::from("1.15.1"));
assert_eq!(server_status.version.protocol, 575);
assert_eq!(server_status.players.max, 100);
assert_eq!(server_status.players.online, 10);
assert_eq!(server_status.players.sample, vec![player]);
assert_eq!(
server_status.description,
Message::new(Payload::text("Description"))
);
}
}

View File

@ -1 +0,0 @@
{"text":"hello client!"}

View File

@ -1 +0,0 @@
{"text":"Message"}

View File

@ -1 +0,0 @@
hello server!

View File

@ -1,3 +0,0 @@
ServerID



View File

@ -1,3 +0,0 @@



View File

@ -1 +0,0 @@
{"text":"Message"}

View File

@ -1 +0,0 @@
7Channel

View File

@ -1 +0,0 @@
7

View File

@ -1 +0,0 @@
Username

View File

@ -1 +0,0 @@
$35ee313b-d89a-41b8-b25e-d32e8aff0389Username

View File

@ -1 +0,0 @@
¾{"version":{"name":"1.15.1","protocol":575},"players":{"max":100,"online":10,"sample":[{"name":"Username","id":"2a1e1912-7103-4add-80fc-91ebc346cbce"}]},"description":{"text":"Description"}}