use std::fmt;
use std::str::FromStr;
use ghast_protocol::{DecodeError, EncodeError, FrameEncoder, PacketFilter, RawPacket, Version};
use crate::common::{
ConfigInbound, ConfigOutbound, Inbound, LoginInbound, Outbound, Pose, Teleport,
};
use crate::interest::Interests;
mod caps;
#[cfg(ghast_modern)]
mod commands;
#[cfg(feature = "v1_12_2")]
mod v1_12_2;
#[cfg(feature = "v1_16_5")]
mod v1_16_5;
#[cfg(feature = "v1_8")]
mod v1_8;
#[cfg(feature = "v26_1")]
pub(crate) mod v26_1;
#[cfg(feature = "v26_2")]
pub(crate) mod v26_2;
#[cfg(feature = "v26_3")]
pub(crate) mod v26_3;
pub use caps::{
Capabilities, CooldownReset, DataSet, InvulnerableEating, ItemCooldownRules, ItemModel,
PhysicsRules, UseStop,
};
#[cfg(feature = "v1_8")]
pub use ghast_protocol::v1_8::V1_8;
#[cfg(feature = "v1_12_2")]
pub use ghast_protocol::v1_12_2::V1_12_2;
#[cfg(feature = "v1_16_5")]
pub use ghast_protocol::v1_16_5::V1_16_5;
#[cfg(feature = "v26_1")]
pub use ghast_protocol::v26_1::V26_1;
#[cfg(feature = "v26_2")]
pub use ghast_protocol::v26_2::V26_2;
#[cfg(feature = "v26_3")]
pub use ghast_protocol::v26_3::V26_3;
#[cfg(feature = "v1_12_2")]
pub use v1_12_2::Wire as Wire1_12;
#[cfg(feature = "v26_1")]
pub use v26_1::Wire as Wire26_1;
#[cfg(feature = "v26_2")]
pub use v26_2::Wire as Wire26_2;
#[cfg(feature = "v26_3")]
pub use v26_3::Wire as Wire26_3;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum GameVersion {
V1_8_9,
V1_12_2,
V1_16_5,
V26_1,
V26_2,
V1_12_1,
V1_16_2,
V1_16_3,
V26_3,
}
impl GameVersion {
pub const ALL: &'static [GameVersion] = &[
GameVersion::V1_8_9,
GameVersion::V1_12_1,
GameVersion::V1_12_2,
GameVersion::V1_16_2,
GameVersion::V1_16_3,
GameVersion::V1_16_5,
GameVersion::V26_1,
GameVersion::V26_2,
GameVersion::V26_3,
];
#[must_use]
pub const fn caps(self) -> &'static Capabilities {
match self {
Self::V1_8_9 => &caps::V1_8_9,
Self::V1_12_2 => &caps::V1_12_2,
Self::V1_16_5 => &caps::V1_16_5,
Self::V26_1 => &caps::V26_1,
Self::V26_2 => &caps::V26_2,
Self::V26_3 => &caps::V26_3,
Self::V1_12_1 => &caps::V1_12_1,
Self::V1_16_2 => &caps::V1_16_2,
Self::V1_16_3 => &caps::V1_16_3,
}
}
pub(crate) const fn instance(self) -> GameVersion {
match self {
Self::V1_12_1 => Self::V1_12_2,
Self::V1_16_2 | Self::V1_16_3 => Self::V1_16_5,
v => v,
}
}
#[must_use]
pub const fn enabled(self) -> bool {
match self {
Self::V1_8_9 => cfg!(feature = "v1_8"),
Self::V1_12_2 => cfg!(feature = "v1_12_2"),
Self::V1_16_5 => cfg!(feature = "v1_16_5"),
Self::V26_1 => cfg!(feature = "v26_1"),
Self::V26_2 => cfg!(feature = "v26_2"),
Self::V26_3 => cfg!(feature = "v26_3"),
Self::V1_12_1 => cfg!(feature = "v1_12_2"),
Self::V1_16_2 | Self::V1_16_3 => cfg!(feature = "v1_16_5"),
}
}
#[must_use]
pub const fn protocol(self) -> i32 {
self.caps().protocol
}
#[must_use]
pub fn protocol_info(self) -> &'static ghast_protocol::ProtocolVersion {
ghast_protocol::versions::by_protocol(self.protocol())
.expect("every GameVersion has a row in the protocol table")
}
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::V1_8_9 => "1.8.9",
Self::V1_12_2 => "1.12.2",
Self::V1_16_5 => "1.16.5",
Self::V26_1 => "26.1",
Self::V26_2 => "26.2",
Self::V26_3 => "26.3",
Self::V1_12_1 => "1.12.1",
Self::V1_16_2 => "1.16.2",
Self::V1_16_3 => "1.16.3",
}
}
#[must_use]
pub const fn combat_1_9(self) -> bool {
self.caps().combat_1_9
}
#[must_use]
pub const fn eye_height(self) -> f64 {
self.caps().eye_height
}
#[must_use]
pub const fn sneak_eye_height(self) -> f64 {
self.caps().sneak_eye_height
}
}
impl fmt::Display for GameVersion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error(
"unsupported Minecraft version `{0}` (supported: 1.8 - 1.8.9, 1.12.1, 1.12.2, 1.16.2 - 1.16.5, 26.1 - 26.1.2, 26.2, 26.3)"
)]
pub struct UnknownVersion(pub String);
impl FromStr for GameVersion {
type Err = UnknownVersion;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.trim() {
"1.8" | "1.8.0" | "1.8.1" | "1.8.2" | "1.8.3" | "1.8.4" | "1.8.5" | "1.8.6"
| "1.8.7" | "1.8.8" | "1.8.9" | "47" => Ok(Self::V1_8_9),
"1.12.1" | "338" => Ok(Self::V1_12_1),
"1.12.2" | "340" => Ok(Self::V1_12_2),
"1.16.2" | "751" => Ok(Self::V1_16_2),
"1.16.3" | "753" => Ok(Self::V1_16_3),
"1.16.4" | "1.16.5" | "754" => Ok(Self::V1_16_5),
"26.1" | "26.1.0" | "26.1.1" | "26.1.2" | "775" => Ok(Self::V26_1),
"26.2" | "26.2.0" | "776" => Ok(Self::V26_2),
"26.3" | "26.3.0" | "777" => Ok(Self::V26_3),
other => Err(UnknownVersion(other.to_owned())),
}
}
}
pub trait ClientVersion: Version + sealed::Sealed {
const GAME: GameVersion;
const CHAT_LIMIT: usize;
fn write_handshake(enc: &mut FrameEncoder, host: &str, port: u16) -> Result<(), EncodeError>;
#[doc(hidden)]
fn write_handshake_for(
enc: &mut FrameEncoder,
version: GameVersion,
host: &str,
port: u16,
) -> Result<(), EncodeError> {
debug_assert_eq!(version.protocol(), Self::GAME.protocol());
Self::write_handshake(enc, host, port)
}
type Wire: Default + fmt::Debug + Send;
#[doc(hidden)]
fn wire_for(version: GameVersion) -> Self::Wire {
let _ = version;
Self::Wire::default()
}
fn write_login_start(
enc: &mut FrameEncoder,
username: &str,
uuid: uuid::Uuid,
) -> Result<(), EncodeError>;
fn write_encryption_response(
enc: &mut FrameEncoder,
shared_secret: &[u8],
verify_token: &[u8],
) -> Result<(), EncodeError>;
fn write_plugin_response(enc: &mut FrameEncoder, message_id: i32) -> Result<(), EncodeError>;
fn decode_login(raw: &RawPacket) -> Result<Option<LoginInbound>, DecodeError>;
fn write_transfer_handshake(
enc: &mut FrameEncoder,
host: &str,
port: u16,
) -> Result<(), EncodeError> {
Self::write_handshake(enc, host, port)
}
fn take_cookies(
wire: &mut Self::Wire,
) -> Vec<(ghast_protocol::types::ByteString, bytes::Bytes)> {
let _ = wire;
Vec::new()
}
fn put_cookies(
wire: &mut Self::Wire,
cookies: Vec<(ghast_protocol::types::ByteString, bytes::Bytes)>,
) {
let _ = (wire, cookies);
}
fn write_login_cookie_response_from(
enc: &mut FrameEncoder,
key: &str,
wire: &mut Self::Wire,
) -> Result<(), EncodeError> {
let _ = wire;
Self::write_login_cookie_response(enc, key)
}
fn write_login_cookie_response(enc: &mut FrameEncoder, key: &str) -> Result<(), EncodeError> {
let _ = (enc, key);
Ok(())
}
fn write_login_acknowledged(enc: &mut FrameEncoder) -> Result<(), EncodeError> {
let _ = enc;
Ok(())
}
fn decode_configuration(
raw: &RawPacket,
wire: &mut Self::Wire,
) -> Result<Option<ConfigInbound>, DecodeError> {
let _ = (raw, wire);
Ok(None)
}
fn write_configuration(
enc: &mut FrameEncoder,
out: &ConfigOutbound,
wire: &mut Self::Wire,
) -> Result<(), EncodeError> {
let _ = (enc, out, wire);
Ok(())
}
fn note_registry(raw: &RawPacket, wire: &mut Self::Wire) {
let _ = (raw, wire);
}
fn write_configuration_acknowledged(enc: &mut FrameEncoder) -> Result<(), EncodeError> {
let _ = enc;
Ok(())
}
fn feed_inventory_config(inv: &mut ghast_inventory::Inventory, wire: &mut Self::Wire) {
let _ = (inv, wire);
}
#[inline(always)]
fn mount_screen_entity(raw: &RawPacket) -> Option<i32> {
let _ = raw;
None
}
fn open_mount_screen(
inv: &mut ghast_inventory::Inventory,
raw: &RawPacket,
mount: Option<(i32, bool, bool)>,
) -> Result<(), DecodeError> {
let _ = (inv, raw, mount);
Ok(())
}
#[inline(always)]
fn prepare_play(out: &[crate::common::Outbound], wire: &mut Self::Wire) {
let _ = (out, wire);
}
fn begin_chat_session(
wire: &mut Self::Wire,
keys: &std::sync::Arc<ghast_auth::chat::ProfileKeys>,
profile_id: uuid::Uuid,
) -> bool {
let _ = (wire, keys, profile_id);
false
}
#[inline]
fn online_mode(wire: &Self::Wire, encrypted: bool) -> bool {
let _ = wire;
encrypted
}
fn write_configuration_start_replies(
enc: &mut FrameEncoder,
wire: &mut Self::Wire,
) -> Result<(), EncodeError> {
let _ = (enc, wire);
Ok(())
}
fn write_wire_replies(
enc: &mut FrameEncoder,
wire: &mut Self::Wire,
) -> Result<(), EncodeError> {
let _ = (enc, wire);
Ok(())
}
fn prediction_sequence(wire: &Self::Wire) -> Option<i32> {
let _ = wire;
None
}
fn check_command(wire: &mut Self::Wire, command: &str) -> crate::dialog::CommandCheck {
let _ = (wire, command);
crate::dialog::CommandCheck::ParseErrors
}
fn play_filter(interests: Interests) -> PacketFilter;
fn decode_play(raw: &RawPacket, wire: &mut Self::Wire) -> Result<Option<Inbound>, DecodeError>;
#[inline]
fn resource_pack(
raw: &RawPacket,
accept: bool,
out: &mut Vec<crate::common::Outbound>,
) -> Result<(), DecodeError> {
let _ = (raw, accept, out);
Ok(())
}
fn inventory_packet(
inv: &mut ghast_inventory::Inventory,
raw: &RawPacket,
) -> Result<Option<ghast_inventory::Outgoing>, DecodeError>;
fn inventory_packet_ids(inv: &ghast_inventory::Inventory) -> &'static [i32] {
let _ = inv;
&[]
}
const INVENTORY: ghast_inventory::Version;
fn configure_inventory(inv: &mut ghast_inventory::Inventory, wire: &Self::Wire) {
let _ = (inv, wire);
}
fn write_play(
enc: &mut FrameEncoder,
out: &Outbound,
wire: &mut Self::Wire,
) -> Result<(), EncodeError>;
fn apply_teleport(pose: &mut Pose, t: &Teleport);
}
pub(crate) trait HasSim {
type Sim: crate::sim::Sim;
fn new_sim(opts: &crate::sim::SimOptions) -> Self::Sim;
}
mod sealed {
#[allow(unnameable_types, reason = "sealed trait pattern")]
pub trait Sealed {}
#[cfg(feature = "v1_8")]
impl Sealed for super::V1_8 {}
#[cfg(feature = "v1_12_2")]
impl Sealed for super::V1_12_2 {}
#[cfg(feature = "v1_16_5")]
impl Sealed for super::V1_16_5 {}
#[cfg(feature = "v26_1")]
impl Sealed for super::V26_1 {}
#[cfg(feature = "v26_2")]
impl Sealed for super::V26_2 {}
#[cfg(feature = "v26_3")]
impl Sealed for super::V26_3 {}
}
#[cfg(any(feature = "v1_8", feature = "v1_12_2"))]
pub(crate) fn legacy_wake_up(raw: &RawPacket) -> Result<Option<i32>, DecodeError> {
let mut r = ghast_protocol::Reader::new(&raw.body);
let id = r.read_varint()?;
Ok((r.read_u8()? == 2).then_some(id))
}
pub(crate) fn truncate_utf16(s: &str, max: usize) -> &str {
let mut units = 0;
for (i, c) in s.char_indices() {
units += c.len_utf16();
if units > max {
return &s[..i];
}
}
s
}
#[cfg(any(feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
pub(crate) const fn legacy_pack_statuses(loadable: bool, accept: bool) -> &'static [i32] {
if !loadable {
&[2]
} else if accept {
&[3, 0]
} else {
&[1]
}
}
#[cfg(any(feature = "v1_12_2", feature = "v1_16_5"))]
pub(crate) fn pack_url_valid(url: &str) -> bool {
let Some((scheme, rest)) = url.split_once(':') else {
return false;
};
let level = scheme == "level";
if !(scheme == "http" || scheme == "https" || level) || rest.is_empty() || rest == "//" {
return false;
}
let authority_end = rest
.strip_prefix("//")
.map_or(0, |a| 2 + a.find(['/', '?', '#']).unwrap_or(a.len()));
let bytes = rest.as_bytes();
let mut fragments = 0;
for (i, &b) in bytes.iter().enumerate() {
match b {
b'%' => {
let hex = |j: usize| bytes.get(j).is_some_and(u8::is_ascii_hexdigit);
if !(hex(i + 1) && hex(i + 2)) {
return false;
}
}
b'#' => {
fragments += 1;
if fragments > 1 {
return false;
}
}
b'[' | b']' if i >= authority_end => return false,
0..=0x20 | 0x7f | b'"' | b'<' | b'>' | b'\\' | b'^' | b'`' | b'{' | b'|' | b'}' => {
return false;
}
_ => {}
}
}
if !rest.is_ascii() && rest.chars().any(|c| c.is_control() || c.is_whitespace()) {
return false;
}
!level || (!url.contains("..") && url.ends_with("/resources.zip"))
}
pub(crate) fn teleport_target(pose: &mut Pose, t: &Teleport) -> (f32, f32) {
use crate::common::teleport_flags as fl;
let mut x = t.x;
let mut y = t.y;
let mut z = t.z;
if t.flags & fl::X != 0 {
x += pose.pos.x;
} else {
pose.motion.x = 0.0;
}
if t.flags & fl::Y != 0 {
y += pose.pos.y;
} else {
pose.motion.y = 0.0;
}
if t.flags & fl::Z != 0 {
z += pose.pos.z;
} else {
pose.motion.z = 0.0;
}
pose.pos = crate::common::Vec3::new(x, y, z);
let mut yaw = t.yaw;
let mut pitch = t.pitch;
if t.flags & fl::PITCH != 0 {
pitch += pose.pitch;
}
if t.flags & fl::YAW != 0 {
yaw += pose.yaw;
}
(yaw, pitch)
}
#[cfg(any(feature = "v1_8", feature = "v1_12_2"))]
pub(crate) fn payload_channel_is(body: &[u8], channel: &[u8]) -> bool {
let mut len = 0usize;
for (k, &b) in body.iter().take(5).enumerate() {
len |= usize::from(b & 0x7f) << (7 * k);
if b & 0x80 == 0 {
return body.get(k + 1..k + 1 + len) == Some(channel);
}
}
false
}
#[cfg(any(feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
pub(crate) fn legacy_title(
action: i32,
text: Option<ghast_protocol::types::ByteString>,
times: (Option<i32>, Option<i32>, Option<i32>),
action_bar: bool,
legacy_reset: bool,
) -> Option<crate::common::Inbound> {
use crate::common::Inbound;
use crate::hud::{Text, TitleOp, TitleTimes};
let a = if action_bar || action < 2 {
action
} else {
action + 1
};
let text = || Text::from_json(text.clone().unwrap_or_default());
let (i, s, o) = (
times.0.unwrap_or(0),
times.1.unwrap_or(0),
times.2.unwrap_or(0),
);
Some(match a {
0 => Inbound::Title(TitleOp::Title(text())),
1 => Inbound::Title(TitleOp::Subtitle(text())),
2 => Inbound::ActionBar(text()),
3 if i < 0 && s < 0 && o < 0 => Inbound::Title(TitleOp::Clear),
3 => Inbound::Title(TitleOp::Times(TitleTimes::new(i, s, o))),
4 => Inbound::Title(TitleOp::Times(TitleTimes::new(0, 0, 0))),
5 if legacy_reset => Inbound::Title(TitleOp::LegacyReset),
5 => Inbound::Title(TitleOp::Reset),
_ => return None,
})
}
#[cfg(any(feature = "v1_12_2", feature = "v1_16_5"))]
#[allow(clippy::too_many_arguments)]
pub(crate) fn legacy_boss_bar(
id: uuid::Uuid,
action: i32,
title: Option<ghast_protocol::types::ByteString>,
health: Option<f32>,
color: Option<i32>,
division: Option<i32>,
flags: Option<u8>,
fog_bit: u8,
) -> Option<crate::common::Inbound> {
use crate::hud::{BossBar, BossBarColor, BossBarOp, BossBarStyle, Text};
let text = || Text::from_json(title.clone().unwrap_or_default());
let style = || {
Some((
BossBarColor::from_wire(color?)?,
BossBarStyle::from_wire(division?)?,
))
};
let f = flags.unwrap_or(0);
Some(crate::common::Inbound::BossBar(match action {
0 => {
let (color, style) = style()?;
let mut bar = BossBar::new(id, text(), health.unwrap_or(0.0), color, style);
bar.darken_screen = f & 1 != 0;
bar.play_music = f & 2 != 0;
bar.create_fog = f & fog_bit != 0;
BossBarOp::Add(bar)
}
1 => BossBarOp::Remove(id),
2 => BossBarOp::Progress(id, health.unwrap_or(0.0)),
3 => BossBarOp::Title(id, text()),
4 => {
let (color, style) = style()?;
BossBarOp::Style { id, color, style }
}
5 => BossBarOp::Flags {
id,
darken_screen: f & 1 != 0,
play_music: f & 2 != 0,
create_fog: None,
},
_ => return None,
}))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sub_versions_share_their_row() {
for &v in GameVersion::ALL {
let (c, base) = (v.caps(), v.instance().caps());
assert_eq!(v.instance().instance(), v.instance());
assert_eq!(v.enabled(), v.instance().enabled());
let row = Capabilities {
version: c.version,
protocol: c.protocol,
..*base
};
assert_eq!(*c, row, "{v}");
}
}
#[test]
fn spectator_rows() {
for &v in GameVersion::ALL {
let modern = v.caps().configuration_state;
assert_eq!(v.caps().spectator_block_click_swings, !modern, "{v}");
assert_eq!(v.caps().spectator_switch_stops_use, modern, "{v}");
}
}
#[test]
fn protocol_rows() {
for &v in GameVersion::ALL {
assert_eq!(v.caps().version, v);
let row = v.protocol_info();
assert_eq!(row.protocol, v.protocol());
assert!(row.enabled || !v.enabled());
assert!(row.game_versions.contains(&v.name()));
}
}
#[test]
fn parse_versions() {
assert_eq!("1.8.8".parse::<GameVersion>().unwrap(), GameVersion::V1_8_9);
assert_eq!("754".parse::<GameVersion>().unwrap(), GameVersion::V1_16_5);
assert_eq!(
"1.12.2".parse::<GameVersion>().unwrap(),
GameVersion::V1_12_2
);
assert_eq!("340".parse::<GameVersion>().unwrap(), GameVersion::V1_12_2);
assert!("1.12".parse::<GameVersion>().is_err());
assert!("1.16.1".parse::<GameVersion>().is_err());
for (s, v, p) in [
("1.12.1", GameVersion::V1_12_1, 338),
("338", GameVersion::V1_12_1, 338),
("1.16.2", GameVersion::V1_16_2, 751),
("751", GameVersion::V1_16_2, 751),
("1.16.3", GameVersion::V1_16_3, 753),
("753", GameVersion::V1_16_3, 753),
("1.16.4", GameVersion::V1_16_5, 754),
] {
assert_eq!(s.parse::<GameVersion>().unwrap(), v, "{s}");
assert_eq!(v.protocol(), p);
}
assert_eq!(GameVersion::V1_8_9.protocol(), 47);
assert_eq!(GameVersion::V1_12_2.protocol(), 340);
assert_eq!(GameVersion::V1_16_5.protocol(), 754);
}
#[test]
fn utf16_truncation() {
assert_eq!(truncate_utf16("hello", 3), "hel");
assert_eq!(truncate_utf16("hello", 10), "hello");
assert_eq!(truncate_utf16("a\u{1F600}b", 2), "a");
assert_eq!(truncate_utf16("a\u{1F600}b", 3), "a\u{1F600}");
}
}