Skip to content

Commit

Permalink
Merge branch 'ecs_rewrite' into ecs-inventory-interact
Browse files Browse the repository at this point in the history
  • Loading branch information
dyc3 committed Jan 20, 2023
2 parents 5e150c7 + 8ea57ac commit 27068bf
Show file tree
Hide file tree
Showing 15 changed files with 400 additions and 27 deletions.
7 changes: 4 additions & 3 deletions crates/packet_inspector/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ edition = "2021"
description = "A simple Minecraft proxy for inspecting packets."

[dependencies]
valence_protocol = { path = "../valence_protocol", version = "0.1.0", features = ["compression"] }
clap = { version = "4.0.30", features = ["derive"] }
tokio = { version = "1", features = ["full"] }
anyhow = "1"
clap = { version = "4.0.30", features = ["derive"] }
regex = "1.6.0"
tokio = { version = "1", features = ["full"] }
tracing-subscriber = "0.3.16"
valence_protocol = { path = "../valence_protocol", version = "0.1.0", features = ["compression"] }
2 changes: 1 addition & 1 deletion crates/packet_inspector/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ For instance, if you only want to print the packets `Foo`, `Bar`, and `Baz`, you
as `^(Foo|Bar|Baz)$` with the `-i` flag.

```sh
cargo r -r -p packet_inspector -- 127.0.0.1:25566 127.0.0.1:25565 '^(Foo|Bar|Baz)$'
cargo r -r -p packet_inspector -- 127.0.0.1:25566 127.0.0.1:25565 -i '^(Foo|Bar|Baz)$'
```

Packets are printed to `stdout` while errors are printed to `stderr`. If you only want to see errors in your terminal,
Expand Down
5 changes: 5 additions & 0 deletions crates/packet_inspector/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use tokio::net::tcp::{OwnedReadHalf, OwnedWriteHalf};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::Semaphore;
use tokio::task::JoinHandle;
use tracing_subscriber::filter::LevelFilter;
use valence_protocol::packets::c2s::handshake::Handshake;
use valence_protocol::packets::c2s::login::{EncryptionResponse, LoginStart};
use valence_protocol::packets::c2s::play::C2sPlayPacket;
Expand Down Expand Up @@ -111,6 +112,10 @@ impl State {

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
tracing_subscriber::fmt()
.with_max_level(LevelFilter::DEBUG)
.init();

let cli = Arc::new(Cli::parse());

let sema = Arc::new(Semaphore::new(cli.max_connections.unwrap_or(100_000)));
Expand Down
5 changes: 3 additions & 2 deletions crates/valence/src/server/packet_manager.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::fmt;
use std::io::ErrorKind;
use std::time::Duration;

Expand Down Expand Up @@ -60,7 +61,7 @@ where

pub async fn recv_packet<'a, P>(&'a mut self) -> Result<P>
where
P: DecodePacket<'a>,
P: DecodePacket<'a> + fmt::Debug,
{
timeout(self.timeout, async {
while !self.dec.has_next_packet()? {
Expand Down Expand Up @@ -259,7 +260,7 @@ pub struct PlayPacketReceiver {
impl PlayPacketReceiver {
pub fn try_next_packet<'a, P>(&'a mut self) -> Result<Option<P>>
where
P: DecodePacket<'a>,
P: DecodePacket<'a> + fmt::Debug,
{
self.dec.try_next_packet()
}
Expand Down
8 changes: 8 additions & 0 deletions crates/valence_nbt/src/from_binary_slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@ pub fn from_binary_slice(slice: &mut &[u8]) -> Result<(Compound, String)> {
let mut state = DecodeState { slice, depth: 0 };

let root_tag = state.read_tag()?;

// For cases such as Block Entity Data in the
// ChunkUpdateAndUpdateLight Packet
// https://wiki.vg/Protocol#Chunk_Data_and_Update_Light
if root_tag == Tag::End {
return Ok((Compound::new(), String::new()));
}

if root_tag != Tag::Compound {
return Err(Error::new_owned(format!(
"expected root tag for compound (got {root_tag})",
Expand Down
5 changes: 3 additions & 2 deletions crates/valence_protocol/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,16 @@ build = "build/main.rs"
[dependencies]
aes = { version = "0.7.5", optional = true }
anyhow = "1.0.66"
bitfield-struct = "0.1.7"
bitfield-struct = "0.3.1"
byteorder = "1.4.3"
bytes = "1.2.1"
cfb8 = { version = "0.7.1", optional = true }
flate2 = { version = "1.0.24", optional = true }
serde = { version = "1.0.147", features = ["derive"] }
serde_json = "1.0.87"
thiserror = "1.0.37"
uuid = "1.2.1"
tracing = "0.1.37"
uuid = { version = "1.2.1", features = ["serde"] }
valence_derive = { version = "0.1.0", path = "../valence_derive" }
valence_nbt = { version = "0.5.0", path = "../valence_nbt" }

Expand Down
17 changes: 11 additions & 6 deletions crates/valence_protocol/src/codec.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use std::fmt;

#[cfg(feature = "encryption")]
use aes::cipher::{AsyncStreamCipher, NewCipher};
use anyhow::{bail, ensure};
use bytes::{Buf, BufMut, BytesMut};
use tracing::debug;

use crate::var_int::{VarInt, VarIntDecodeError};
use crate::{DecodePacket, Encode, EncodePacket, Result, MAX_PACKET_SIZE};
Expand Down Expand Up @@ -285,7 +288,7 @@ impl PacketDecoder {

pub fn try_next_packet<'a, P>(&'a mut self) -> Result<Option<P>>
where
P: DecodePacket<'a>,
P: DecodePacket<'a> + fmt::Debug,
{
self.buf.advance(self.cursor);
self.cursor = 0;
Expand Down Expand Up @@ -345,11 +348,13 @@ impl PacketDecoder {
#[cfg(not(feature = "compression"))]
let packet = P::decode_packet(&mut r)?;

ensure!(
r.is_empty(),
"packet contents were not read completely ({} bytes remain)",
r.len()
);
if !r.is_empty() {
let remaining = r.len();

debug!("packet after partial decode ({remaining} bytes remain): {packet:?}");

bail!("packet contents were not read completely ({remaining} bytes remain)");
}

let total_packet_len = VarInt(packet_len).written_size() + packet_len as usize;
self.cursor = total_packet_len;
Expand Down
9 changes: 6 additions & 3 deletions crates/valence_protocol/src/packets/c2s.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,9 +143,12 @@ pub mod play {
pub message: &'a str,
pub timestamp: u64,
pub salt: u64,
pub signature: &'a [u8],
pub signed_preview: bool,
pub acknowledgement: MessageAcknowledgment<'a>,
pub signature: Option<&'a [u8; 256]>,
pub message_count: VarInt,
// This is a bitset of 20; each bit represents one
// of the last 20 messages received and whether or not
// the message was acknowledged by the client
pub acknowledgement: &'a [u8; 3],
}

#[derive(Clone, Debug, Encode, EncodePacket, Decode, DecodePacket)]
Expand Down
69 changes: 60 additions & 9 deletions crates/valence_protocol/src/packets/s2c.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ use crate::raw_bytes::RawBytes;
use crate::text::Text;
use crate::types::{
AttributeProperty, BossBarAction, ChunkDataBlockEntity, Difficulty, GameEventKind, GameMode,
GlobalPos, PlayerAbilitiesFlags, SignedProperty, SoundCategory, SyncPlayerPosLookFlags,
TagGroup,
GlobalPos, PlayerAbilitiesFlags, SignedProperty, SoundCategory, Statistic,
SyncPlayerPosLookFlags, TagGroup,
};
use crate::username::Username;
use crate::var_int::VarInt;
Expand All @@ -21,7 +21,10 @@ use crate::LengthPrefixedArray;
pub mod commands;
pub mod declare_recipes;
pub mod particle;
pub mod player_chat_message;
pub mod player_info_update;
pub mod set_equipment;
pub mod update_advancements;
pub mod update_recipe_book;

pub mod status {
Expand Down Expand Up @@ -102,7 +105,10 @@ pub mod login {
pub mod play {
use commands::Node;
pub use particle::ParticleS2c;
pub use player_chat_message::PlayerChatMessage;
pub use player_info_update::PlayerInfoUpdate;
pub use set_equipment::SetEquipment;
pub use update_advancements::UpdateAdvancements;
pub use update_recipe_book::UpdateRecipeBook;

use super::*;
Expand Down Expand Up @@ -149,6 +155,12 @@ pub mod play {
pub animation: u8, // TODO: use Animation enum.
}

#[derive(Clone, Debug, Encode, EncodePacket, Decode, DecodePacket)]
#[packet_id = 0x04]
pub struct AwardStatistics {
pub statistics: Vec<Statistic>,
}

#[derive(Copy, Clone, Debug, Encode, EncodePacket, Decode, DecodePacket)]
#[packet_id = 0x05]
pub struct AcknowledgeBlockChange {
Expand Down Expand Up @@ -351,6 +363,29 @@ pub mod play {
pub block_light_arrays: &'a [LengthPrefixedArray<u8, 2048>],
}

#[derive(Clone, Debug, Encode, EncodePacket, Decode, DecodePacket)]
#[packet_id = 0x21]
pub struct WorldEvent {
pub event: i32,
pub location: BlockPos,
pub data: i32,
pub disable_relative_volume: bool,
}

#[derive(Clone, Debug, Encode, EncodePacket, Decode, DecodePacket)]
#[packet_id = 0x23]
pub struct UpdateLight {
pub chunk_x: VarInt,
pub chunk_z: VarInt,
pub trust_edges: bool,
pub sky_light_mask: Vec<u64>,
pub block_light_mask: Vec<u64>,
pub empty_sky_light_mask: Vec<u64>,
pub empty_block_light_mask: Vec<u64>,
pub sky_light_arrays: Vec<LengthPrefixedArray<u8, 2048>>,
pub block_light_arrays: Vec<LengthPrefixedArray<u8, 2048>>,
}

#[derive(Clone, Debug, Encode, EncodePacket, Decode, DecodePacket)]
#[packet_id = 0x24]
pub struct LoginPlay<'a> {
Expand Down Expand Up @@ -440,13 +475,6 @@ pub mod play {
pub fov_modifier: f32,
}

#[derive(Clone, Debug, Encode, EncodePacket, Decode, DecodePacket)]
#[packet_id = 0x31]
pub struct PlayerChatMessage<'a> {
// TODO: A bunch of crap.
pub data: RawBytes<'a>,
}

#[derive(Clone, Debug, Encode, EncodePacket, Decode, DecodePacket)]
#[packet_id = 0x34]
pub struct CombatDeath {
Expand Down Expand Up @@ -610,6 +638,14 @@ pub mod play {
pub food_saturation: f32,
}

#[derive(Clone, Debug, Encode, EncodePacket, Decode, DecodePacket)]
#[packet_id = 0x55]
pub struct SetPassengers {
/// Vehicle's entity id
pub entity_id: VarInt,
pub passengers: Vec<VarInt>,
}

#[derive(Clone, Debug, Encode, EncodePacket, Decode, DecodePacket)]
#[packet_id = 0x59]
pub struct SetSubtitleText(pub Text);
Expand Down Expand Up @@ -676,6 +712,14 @@ pub mod play {
pub footer: Text,
}

#[derive(Copy, Clone, Debug, Encode, EncodePacket, Decode, DecodePacket)]
#[packet_id = 0x63]
pub struct PickupItem {
pub collected_entity_id: VarInt,
pub collector_entity_id: VarInt,
pub pickup_item_count: VarInt,
}

#[derive(Copy, Clone, Debug, Encode, EncodePacket, Decode, DecodePacket)]
#[packet_id = 0x64]
pub struct TeleportEntity {
Expand Down Expand Up @@ -716,6 +760,7 @@ pub mod play {
SpawnExperienceOrb,
SpawnPlayer,
EntityAnimationS2c,
AwardStatistics,
AcknowledgeBlockChange,
SetBlockDestroyStage,
BlockEntityData,
Expand All @@ -737,6 +782,8 @@ pub mod play {
WorldBorderInitialize,
KeepAliveS2c,
ChunkDataAndUpdateLight<'a>,
WorldEvent,
UpdateLight,
ParticleS2c,
LoginPlay<'a>,
UpdateEntityPosition,
Expand All @@ -763,8 +810,10 @@ pub mod play {
SetDefaultSpawnPosition,
SetEntityMetadata<'a>,
SetEntityVelocity,
SetEquipment,
SetExperience,
SetHealth,
SetPassengers,
SetSubtitleText,
UpdateTime,
SetTitleText,
Expand All @@ -773,7 +822,9 @@ pub mod play {
SoundEffect,
SystemChatMessage,
SetTabListHeaderAndFooter,
PickupItem,
TeleportEntity,
UpdateAdvancements<'a>,
UpdateAttributes<'a>,
FeatureFlags<'a>,
DeclareRecipes<'a>,
Expand Down
Loading

0 comments on commit 27068bf

Please sign in to comment.