361 lines
12 KiB
Python
361 lines
12 KiB
Python
"""Minimal protocol support for current Java Edition releases (26.3/777).
|
|
|
|
This deliberately implements only status, offline login, configuration, keepalive,
|
|
position acknowledgement, and unsigned chat command traffic. It is enough for
|
|
headless clients that need to remain connected and interact with server plugins.
|
|
"""
|
|
import io
|
|
import json
|
|
import os
|
|
|
|
from minecraft.networking.packets import Packet
|
|
from minecraft.networking.types import (
|
|
Boolean, Byte, Double, Float, Long, String, TrailingByteArray, Type, UUID,
|
|
UnsignedByte, VarInt,
|
|
)
|
|
from minecraft.networking.connection import PacketReactor
|
|
|
|
|
|
def trace(message):
|
|
if os.getenv('PYCRAFT_TRACE'):
|
|
print('[pyCraft/777] ' + message, flush=True)
|
|
|
|
|
|
def nbt_plain(value):
|
|
raw = getattr(value, 'value', value)
|
|
if hasattr(raw, 'items'):
|
|
return {str(k): nbt_plain(v) for k, v in raw.items()}
|
|
if isinstance(raw, (list, tuple)):
|
|
return [nbt_plain(v) for v in raw]
|
|
return raw
|
|
|
|
|
|
def read_anonymous_nbt(file_object):
|
|
import functools
|
|
import pynbt
|
|
|
|
stream = getattr(file_object, 'bytes', file_object)
|
|
start = stream.tell()
|
|
raw = stream.read()
|
|
if not raw:
|
|
return None
|
|
wrapped = io.BytesIO(raw)
|
|
tag_id = wrapped.read(1)[0]
|
|
if tag_id == 0:
|
|
consumed = 1
|
|
result = None
|
|
else:
|
|
reader = functools.partial(pynbt._read_big, wrapped)
|
|
reader.src = wrapped
|
|
result = pynbt._tags[tag_id].read(reader, has_name=False)
|
|
consumed = wrapped.tell()
|
|
stream.seek(start + consumed)
|
|
return result
|
|
|
|
|
|
class LoginSuccess(Packet):
|
|
id = 0x02
|
|
packet_name = "login success"
|
|
definition = [{'uuid': UUID}, {'username': String}]
|
|
|
|
|
|
class LoginAcknowledged(Packet):
|
|
id = 0x03
|
|
packet_name = "login acknowledged"
|
|
definition = []
|
|
|
|
|
|
class ClientSettings(Packet):
|
|
id = 0x00
|
|
packet_name = "client settings"
|
|
definition = [
|
|
{'locale': String}, {'view_distance': Byte}, {'chat_flags': VarInt},
|
|
{'chat_colors': Boolean}, {'skin_parts': UnsignedByte},
|
|
{'main_hand': VarInt}, {'enable_text_filtering': Boolean},
|
|
{'enable_server_listing': Boolean}, {'particle_status': VarInt},
|
|
]
|
|
|
|
|
|
class CodeOfConduct(Packet):
|
|
id = 0x13
|
|
packet_name = "code of conduct"
|
|
|
|
def read(self, file_object):
|
|
self.payload = file_object.read()
|
|
try:
|
|
self.dialog = read_anonymous_nbt(io.BytesIO(self.payload))
|
|
self.dialog_text = json.dumps(nbt_plain(self.dialog),
|
|
ensure_ascii=False)
|
|
except Exception as exc:
|
|
self.dialog_text = 'could not decode ({})'.format(exc)
|
|
|
|
|
|
class ConfigurationCustomPayload(Packet):
|
|
id = 0x01
|
|
packet_name = "configuration custom payload"
|
|
definition = [{'channel': String}, {'data': TrailingByteArray}]
|
|
|
|
|
|
class FinishConfiguration(Packet):
|
|
id = 0x03
|
|
packet_name = "finish configuration"
|
|
definition = []
|
|
|
|
|
|
class ConfigurationKeepAlive(Packet):
|
|
id = 0x04
|
|
packet_name = "keep alive"
|
|
definition = [{'keep_alive_id': Long}]
|
|
|
|
|
|
class SelectKnownPacks(Packet):
|
|
id = 0x0F
|
|
packet_name = "select known packs"
|
|
|
|
def read(self, file_object):
|
|
self.packs = []
|
|
for _ in range(VarInt.read(file_object)):
|
|
self.packs.append((String.read(file_object), String.read(file_object),
|
|
String.read(file_object)))
|
|
|
|
|
|
class KnownPacksResponse(Packet):
|
|
id = 0x07
|
|
packet_name = "select known packs response"
|
|
|
|
def write_fields(self, packet_buffer):
|
|
packs = getattr(self, 'packs', ())
|
|
VarInt.send(len(packs), packet_buffer)
|
|
for namespace, pack_id, version in packs:
|
|
String.send(namespace, packet_buffer)
|
|
String.send(pack_id, packet_buffer)
|
|
String.send(version, packet_buffer)
|
|
|
|
|
|
class PlayerLoaded(Packet):
|
|
id = 0x2C
|
|
packet_name = "player loaded"
|
|
definition = []
|
|
|
|
|
|
class KeepAlive(Packet):
|
|
id = 0x1C
|
|
packet_name = "keep alive"
|
|
definition = [{'keep_alive_id': Long}]
|
|
|
|
|
|
class KeepAliveClientbound(Packet):
|
|
id = 0x2D
|
|
packet_name = "keep alive"
|
|
definition = [{'keep_alive_id': Long}]
|
|
|
|
|
|
class TeleportPosition(Packet):
|
|
id = 0x49
|
|
packet_name = "player position and look"
|
|
definition = [
|
|
{'teleport_id': VarInt},
|
|
{'x': Double}, {'y': Double}, {'z': Double},
|
|
{'velocity_x': Double}, {'velocity_y': Double}, {'velocity_z': Double},
|
|
{'yaw': Float}, {'pitch': Float},
|
|
]
|
|
|
|
|
|
class TeleportConfirm(Packet):
|
|
id = 0x00
|
|
packet_name = "accept teleportation"
|
|
definition = [
|
|
{'teleport_id': VarInt},
|
|
{'x': Double}, {'y': Double}, {'z': Double},
|
|
{'yaw': Float}, {'pitch': Float},
|
|
]
|
|
|
|
|
|
class AnonymousNBT(Type):
|
|
"""Minecraft's unnamed NBT root used by chat components since 1.20.5."""
|
|
@staticmethod
|
|
def read(file_object):
|
|
return read_anonymous_nbt(file_object)
|
|
|
|
|
|
class SystemChat(Packet):
|
|
id = 0x7C
|
|
packet_name = "system chat"
|
|
definition = [{'content': AnonymousNBT}, {'is_action_bar': Boolean}]
|
|
|
|
|
|
class PlayLogin(Packet):
|
|
id = 0x32
|
|
packet_name = "play login"
|
|
|
|
def read(self, file_object):
|
|
self.payload = file_object.read()
|
|
|
|
|
|
class PlayDisconnect(Packet):
|
|
id = 0x20
|
|
packet_name = "disconnect"
|
|
definition = [{'reason': AnonymousNBT}]
|
|
|
|
|
|
class ChatCommand(Packet):
|
|
id = 0x07
|
|
packet_name = "chat command"
|
|
definition = [{'command': String}]
|
|
|
|
|
|
class AuthMeDialogAction(Packet):
|
|
packet_name = "AuthMe dialog action"
|
|
action_id = None
|
|
password = None
|
|
|
|
def write_fields(self, packet_buffer):
|
|
String.send(self.action_id, packet_buffer)
|
|
if self.password is None:
|
|
# Length-prefixed optional NBT payload: an End tag represents None.
|
|
VarInt.send(1, packet_buffer)
|
|
packet_buffer.send(b'\x00')
|
|
else:
|
|
import pynbt
|
|
nbt = pynbt.TAG_Compound({
|
|
'password': pynbt.TAG_String(self.password),
|
|
})
|
|
stream = io.BytesIO()
|
|
pynbt.NBTFile(value=nbt).save(stream)
|
|
named_nbt = stream.getvalue()
|
|
anonymous_nbt = named_nbt[:1] + named_nbt[3:]
|
|
VarInt.send(len(anonymous_nbt), packet_buffer)
|
|
packet_buffer.send(anonymous_nbt)
|
|
|
|
|
|
class CancelPrejoinDialog(AuthMeDialogAction):
|
|
id = 0x08
|
|
action_id = 'authme:prejoin-register/cancel'
|
|
|
|
|
|
class CancelPostjoinDialog(AuthMeDialogAction):
|
|
id = 0x44
|
|
action_id = 'authme:postjoin-register/cancel'
|
|
|
|
|
|
class CancelPostjoinLoginDialog(AuthMeDialogAction):
|
|
id = 0x44
|
|
action_id = 'authme:postjoin-login/cancel'
|
|
|
|
|
|
class SubmitPrejoinLoginDialog(AuthMeDialogAction):
|
|
id = 0x08
|
|
action_id = 'authme:prejoin-login/submit'
|
|
|
|
|
|
class SubmitPostjoinLoginDialog(AuthMeDialogAction):
|
|
id = 0x44
|
|
action_id = 'authme:postjoin-login/submit'
|
|
|
|
|
|
class PlayShowDialog(Packet):
|
|
id = 0x8F
|
|
packet_name = "show dialog"
|
|
|
|
def read(self, file_object):
|
|
self.payload = file_object.read()
|
|
# Length-prefixed optional NBT payload: an End tag represents None.
|
|
VarInt.send(1, packet_buffer)
|
|
packet_buffer.send(b'\x00')
|
|
|
|
|
|
class ModernLoginReactor(PacketReactor):
|
|
@staticmethod
|
|
def get_clientbound_packets(_context):
|
|
from minecraft.networking.packets.clientbound.login import (
|
|
DisconnectPacket, EncryptionRequestPacket, SetCompressionPacket,
|
|
PluginRequestPacket,
|
|
)
|
|
return {DisconnectPacket, EncryptionRequestPacket, SetCompressionPacket,
|
|
PluginRequestPacket, LoginSuccess}
|
|
|
|
def react(self, packet):
|
|
if packet.packet_name == 'base':
|
|
trace('unhandled login packet 0x{:02x}'.format(packet.id))
|
|
# Re-use pyCraft's standard offline encryption/compression behavior.
|
|
from minecraft.networking.connection import LoginReactor
|
|
if packet.packet_name == "login success":
|
|
self.connection.write_packet(LoginAcknowledged(), force=True)
|
|
self.connection.reactor = ModernConfigurationReactor(self.connection)
|
|
self.connection.write_packet(ClientSettings(
|
|
locale='en_us', view_distance=8, chat_flags=0,
|
|
chat_colors=True, skin_parts=0x7f, main_hand=1,
|
|
enable_text_filtering=False, enable_server_listing=True,
|
|
particle_status=0), force=True)
|
|
return
|
|
LoginReactor.react(self, packet)
|
|
|
|
|
|
class ModernConfigurationReactor(PacketReactor):
|
|
@staticmethod
|
|
def get_clientbound_packets(_context):
|
|
return {FinishConfiguration, ConfigurationKeepAlive, SelectKnownPacks,
|
|
ConfigurationCustomPayload, CodeOfConduct}
|
|
|
|
def react(self, packet):
|
|
if packet.packet_name == 'base':
|
|
trace('unhandled configuration packet 0x{:02x}'.format(packet.id))
|
|
elif packet.packet_name == "configuration custom payload":
|
|
trace('configuration payload channel={!r} bytes={}'.format(
|
|
packet.channel, len(packet.data)))
|
|
elif packet.packet_name == "code of conduct":
|
|
print('[server AuthMe registration dialog] ' + packet.dialog_text, flush=True)
|
|
try:
|
|
dialog = json.loads(packet.dialog_text)
|
|
title = dialog.get('title', {}).get('text', '').lower()
|
|
except (TypeError, ValueError, AttributeError):
|
|
title = 'register'
|
|
self.connection.authme_mode = 'login' if 'login' in title else 'register'
|
|
if self.connection.authme_mode == 'login':
|
|
print('[AuthMe] submitting the pre-join login form.', flush=True)
|
|
self.connection.write_packet(SubmitPrejoinLoginDialog(
|
|
password=self.connection.authme_password), force=True)
|
|
else:
|
|
print('[AuthMe] cancelling the pre-join registration form to use /register.', flush=True)
|
|
self.connection.write_packet(CancelPrejoinDialog(), force=True)
|
|
if packet.packet_name == "keep alive":
|
|
self.connection.write_packet(ConfigurationKeepAlive(
|
|
keep_alive_id=packet.keep_alive_id), force=True)
|
|
elif packet.packet_name == "select known packs":
|
|
trace('negotiating {} known packs'.format(len(packet.packs)))
|
|
self.connection.write_packet(KnownPacksResponse(
|
|
packs=packet.packs), force=True)
|
|
elif packet.packet_name == "finish configuration":
|
|
print('[pyCraft/777] configuration complete', flush=True)
|
|
self.connection.write_packet(FinishConfiguration(), force=True)
|
|
self.connection.reactor = ModernPlayingReactor(self.connection)
|
|
self.connection.spawned = True
|
|
|
|
|
|
class ModernPlayingReactor(PacketReactor):
|
|
@staticmethod
|
|
def get_clientbound_packets(_context):
|
|
return {KeepAliveClientbound, SystemChat, PlayDisconnect, TeleportPosition,
|
|
PlayShowDialog, PlayLogin}
|
|
|
|
def react(self, packet):
|
|
if packet.packet_name == 'base':
|
|
trace('unhandled play packet 0x{:02x}'.format(packet.id))
|
|
if packet.packet_name == "keep alive":
|
|
self.connection.write_packet(KeepAlive(
|
|
keep_alive_id=packet.keep_alive_id), force=True)
|
|
elif packet.packet_name == "play login":
|
|
self.connection.write_packet(PlayerLoaded(), force=True)
|
|
elif packet.packet_name == "player position and look":
|
|
self.connection.write_packet(TeleportConfirm(
|
|
teleport_id=packet.teleport_id, x=packet.x, y=packet.y,
|
|
z=packet.z, yaw=packet.yaw, pitch=packet.pitch), force=True)
|
|
elif packet.packet_name == "show dialog":
|
|
# Dialog actions are handled by the application so it can choose
|
|
# a text command or other AuthMe flow.
|
|
pass
|
|
elif packet.packet_name == "disconnect":
|
|
print('[server disconnect] ' + json.dumps(
|
|
nbt_plain(packet.reason), ensure_ascii=False), flush=True)
|
|
self.connection.disconnect()
|