Add 4 tests in 'test_connection.py' and fix related bugs.

This commit is contained in:
joo committed 2016-06-18 18:22:18 +01:00
1 parent 3ff7662684
commit ce63626bb1
7 files changed
+457 -132

No files matched your search

+60 -33
View File
@@ -3,7 +3,6 @@ from __future__ import print_function
from collections import deque
from threading import Lock
from zlib import decompress
from itertools import *
import threading
import socket
import time
@@ -21,6 +20,7 @@ from . import encryption
from .. import SUPPORTED_PROTOCOL_VERSIONS
from .. import SUPPORTED_MINECRAFT_VERSIONS
class ConnectionContext(object):
"""A ConnectionContext encapsulates the static configuration parameters
shared by the Connection class with other classes, such as Packet.
@@ -29,18 +29,16 @@ class ConnectionContext(object):
def __init__(self, **kwds):
self.protocol_version = kwds.get('protocol_version')
class _ConnectionOptions(object):
def __init__(self,
address=None,
port=None,
compression_threshold=-1,
compression_enabled=False
):
def __init__(self, address=None, port=None, compression_threshold=-1,
compression_enabled=False):
self.address = address
self.port = port
self.compression_threshold = compression_threshold
self.compression_enabled = compression_enabled
class Connection(object):
"""This class represents a connection to a minecraft
server, it handles everything from connecting, sending packets to
@@ -50,9 +48,10 @@ class Connection(object):
self,
address,
port,
auth_token,
initial_version=None, # A Minecraft version str or protocol version int.
allowed_versions=None # A set of versions as above.
auth_token=None,
username=None,
initial_version=None,
allowed_versions=None,
):
"""Sets up an instance of this object to be able to connect to a
minecraft server.
@@ -63,6 +62,16 @@ class Connection(object):
:param address: address of the server to connect to
:param port(int): port of the server to connect to
:param auth_token: :class:`authentication.AuthenticationToken` object.
If None, no authentication is attempted and the
server is assumed to be running in offline mode.
:param username: Username string; only applicable in offline mode.
:param initial_version: A Minecraft version string or protocol version
number to use as a first guess when connecting
to the server.
:param allowed_versions: A set of versions, each being a Minecraft
version string or protocol version number,
restricting the versions that the client may
use in connecting to the server.
"""
self._write_lock = Lock()
@@ -83,7 +92,8 @@ class Connection(object):
if allowed_versions is None:
self.allowed_proto_versions = SUPPORTED_PROTOCOL_VERSIONS
else:
self.allowed_proto_versions = set(map(proto_version, allowed_versions))
allowed_version = set(map(proto_version, allowed_versions))
self.allowed_proto_versions = allowed_version
if initial_version is None:
initial_proto_version = max(self.allowed_proto_versions)
@@ -96,6 +106,7 @@ class Connection(object):
self.options.address = address
self.options.port = port
self.auth_token = auth_token
self.username = username
# The reactor handles all the default responses to packets,
# it should be changed per networking state
@@ -176,14 +187,17 @@ class Connection(object):
self.spawned = False
with self._write_lock:
self._outgoing_packet_queue = deque()
self._connect()
self._handshake()
self.reactor = LoginReactor(self)
self._start_network_thread()
login_start_packet = packets.LoginStartPacket()
login_start_packet.name = self.auth_token.profile.name
if self.auth_token:
login_start_packet.name = self.auth_token.profile.name
else:
login_start_packet.name = self.username
self.write_packet(login_start_packet)
def _connect(self):
@@ -195,7 +209,7 @@ class Connection(object):
# the server.
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect((self.options.address, self.options.port))
self.file_object = self.socket.makefile("rb")
self.file_object = self.socket.makefile("rb", 0)
def _handshake(self, next_state=2):
handshake = packets.HandShakePacket()
@@ -206,6 +220,7 @@ class Connection(object):
self.write_packet(handshake)
class NetworkingThread(threading.Thread):
def __init__(self, connection):
threading.Thread.__init__(self)
@@ -247,6 +262,15 @@ class NetworkingThread(threading.Thread):
self.connection.file_object)
while packet:
num_packets += 1
# Do not raise an IOError if it occurred while a disconnect
# packet was received, as this may be part of an orderly
# disconnection.
if packet.packet_name == 'disconnect' and \
exc_info is not None and \
isinstance(exc_info[1], IOError):
exc_info = None
try:
self.connection.reactor.react(packet)
for listener in self.connection.packet_listeners:
@@ -256,6 +280,7 @@ class NetworkingThread(threading.Thread):
if num_packets >= 50:
break
packet = self.connection.reactor.read_packet(
self.connection.file_object)
@@ -274,6 +299,7 @@ class IgnorePacket(Exception):
"""
pass
class PacketReactor(object):
"""
Reads and reacts to packets
@@ -293,7 +319,7 @@ class PacketReactor(object):
def read_packet(self, stream):
ready_to_read = select.select([stream], [], [], self.TIME_OUT)[0]
if stream in ready_to_read:
if ready_to_read:
length = VarInt.read(stream)
packet_data = packets.PacketBuffer()
@@ -346,8 +372,8 @@ class LoginReactor(PacketReactor):
if packet.server_id != '-':
server_id = encryption.generate_verification_hash(
packet.server_id, secret, packet.public_key)
self.connection.auth_token.join(server_id)
if self.connection.auth_token is not None:
self.connection.auth_token.join(server_id)
encryption_response = packets.EncryptionResponsePacket()
encryption_response.shared_secret = encrypted_secret
@@ -372,31 +398,32 @@ class LoginReactor(PacketReactor):
# (Note: it is known how the disconnect messages are formatted for
# official servers within SUPPORTED_MINECRAFT_VERSIONS, but in case
# new versions are added, this section may need to be updated.)
try: data = json.loads(packet.json_data)
except ValueError: pass
try:
data = json.loads(packet.json_data)
except ValueError:
pass
if isinstance(data, dict) and 'text' in data:
data = data['text']
if not isinstance(data, (str, unicode)): return
if not isinstance(data, (str, unicode)):
return
match = re.match(
r"(Outdated client! Please use"
r"|Outdated server! I'm still on) (?P<version>.*)", data)
if not match: return
if not match:
return
version = match.group('version')
if version in SUPPORTED_MINECRAFT_VERSIONS:
new_version = SUPPORTED_MINECRAFT_VERSIONS[version]
elif data.startswith('Outdated client!'):
new_version = max(SUPPORTED_PROTOCOL_VERSIONS)
new_version = max(SUPPORTED_PROTOCOL_VERSIONS)
elif data.startswith('Outdated server!'):
new_version = min(SUPPORTED_PROTOCOL_VERSIONS)
if (new_version != self.connection.context.protocol_version
and new_version in self.connection.allowed_proto_versions):
# Ignore this disconnect packet and reconnect with the new protocol
# version, making it appear (on the client side) as if the client
# had initially connected with the (hopefully) correct version.
old_version = self.connection.context.protocol_version
print('Warning: connection using protocol version %d refused with '
'message "%s". Reconnecting with protocol version %d.'
% (old_version, data, new_version), file=sys.stderr)
if new_version != self.connection.context.protocol_version \
and new_version in self.connection.allowed_proto_versions:
# Ignore this disconnect packet and reconnect with the new
# protocol version, making it appear (on the client side) as if
# the client had initially connected with the (hopefully)
# correct version.
self.connection.context.protocol_version = new_version
self.connection.connect()
raise IgnorePacket
@@ -408,6 +435,7 @@ class LoginReactor(PacketReactor):
self.connection.options.compression_threshold = packet.threshold
self.connection.options.compression_enabled = True
class PlayingReactor(PacketReactor):
get_clientbound_packets = staticmethod(packets.state_playing_clientbound)
@@ -442,13 +470,12 @@ class PlayingReactor(PacketReactor):
print(packet.json_data) # TODO: handle propagating this back
'''
class StatusReactor(PacketReactor):
get_clientbound_packets = staticmethod(packets.state_status_clientbound)
def react(self, packet):
if packet.packet_name == "response":
import json
print(json.loads(packet.json_response))
ping_packet = packets.PingPacket()
+1
View File
@@ -73,6 +73,7 @@ class EncryptedFileObjectWrapper(object):
def fileno(self):
return self.actual_file_object.fileno()
class EncryptedSocketWrapper(object):
def __init__(self, socket, encryptor, decryptor):
self.actual_socket = socket
+168 -79
View File
@@ -69,7 +69,8 @@ class Packet(object):
# definition for the given ConnectionContext. This may be necessary
# if the layout has changed across protocol versions, for example; or
# 3. Override the methods `read' and/or `write' in a subclass. This may be
# necessary if the packet layout cannot be described as a list of fields.
# necessary if the packet layout cannot be described as a list of
# fields.
@classmethod
def get_definition(cls, context):
return cls.definition
@@ -81,7 +82,7 @@ class Packet(object):
@property
def context(self):
return self._context
@context.setter
def context(self, _context):
self._context = _context
@@ -135,6 +136,15 @@ class Packet(object):
VarInt.send(len(packet_buffer.get_writable()), socket) # Packet Size
socket.send(packet_buffer.get_writable()) # Packet Payload
def __str__(self):
str = type(self).__name__
if self.id is not None:
str = '0x%02X %s' % (self.id, str)
if self.definition is not None:
fields = {a: getattr(self, a) for d in self.definition for a in d}
str = '%s %s' % (str, fields)
return str
# Handshake State
# ==============
@@ -150,13 +160,16 @@ class HandShakePacket(Packet):
def state_handshake_clientbound(context):
return {
}
def state_handshake_serverbound(context):
return {
HandShakePacket
}
# Status State
# ==============
class ResponsePacket(Packet):
@@ -272,20 +285,27 @@ class KeepAlivePacket(Packet):
definition = [
{'keep_alive_id': VarInt}]
class KeepAlivePacketClientbound(KeepAlivePacket):
get_id = staticmethod(lambda context:
0x1F if context.protocol_version >= 107 else
0x00)
@staticmethod
def get_id(context):
return 0x1F if context.protocol_version >= 107 else \
0x00
class KeepAlivePacketServerbound(KeepAlivePacket):
get_id = staticmethod(lambda context:
0x0B if context.protocol_version >= 107 else
0x00)
@staticmethod
def get_id(context):
return 0x0B if context.protocol_version >= 107 else \
0x00
class JoinGamePacket(Packet):
get_id = staticmethod(lambda context:
0x23 if context.protocol_version >= 107 else
0x01)
@staticmethod
def get_id(context):
return 0x23 if context.protocol_version >= 107 else \
0x01
packet_name = "join game"
get_definition = staticmethod(lambda context: [
{'entity_id': Integer},
@@ -298,9 +318,11 @@ class JoinGamePacket(Packet):
class ChatMessagePacket(Packet):
get_id = staticmethod(lambda context:
0x0F if context.protocol_version >= 107 else
0x02)
@staticmethod
def get_id(context):
return 0x0F if context.protocol_version >= 107 else \
0x02
packet_name = "chat message"
definition = [
{'json_data': String},
@@ -308,9 +330,11 @@ class ChatMessagePacket(Packet):
class PlayerPositionAndLookPacket(Packet):
get_id = staticmethod(lambda context:
0x2E if context.protocol_version >= 107 else
0x08)
@staticmethod
def get_id(context):
return 0x2E if context.protocol_version >= 107 else \
0x08
packet_name = "player position and look"
get_definition = staticmethod(lambda context: [
{'x': Double},
@@ -322,37 +346,57 @@ class PlayerPositionAndLookPacket(Packet):
{'teleport_id': VarInt} if context.protocol_version >= 107 else {},
])
FLAG_REL_X = 0x01
FLAG_REL_Y = 0x02
FLAG_REL_Z = 0x04
FLAG_REL_YAW = 0x08
FLAG_REL_X = 0x01
FLAG_REL_Y = 0x02
FLAG_REL_Z = 0x04
FLAG_REL_YAW = 0x08
FLAG_REL_PITCH = 0x10
class PositionAndLook(object):
__slots__ = 'x', 'y', 'z', 'yaw', 'pitch'
def __init__(self, **kwds):
for attr in self.__slots__:
setattr(self, attr, kwds.get(attr))
# Update a PositionAndLook instance using this packet.
def apply(self, target):
if self.flags & self.FLAG_REL_X: target.x += self.x
else: target.x = self.x
if self.flags & self.FLAG_REL_Y: target.y += self.y
else: target.y = self.y
if self.flags & self.FLAG_REL_Z: target.z += self.z
else: target.z = self.z
if self.flags & self.FLAG_REL_YAW: target.yaw += self.yaw
else: target.yaw = self.yaw
if self.flags & self.FLAG_REL_PITCH: target.pitch += self.pitch
else: target.pitch = self.pitch
# pylint: disable=no-member
if self.flags & self.FLAG_REL_X:
target.x += self.x
else:
target.x = self.x
if self.flags & self.FLAG_REL_Y:
target.y += self.y
else:
target.y = self.y
if self.flags & self.FLAG_REL_Z:
target.z += self.z
else:
target.z = self.z
if self.flags & self.FLAG_REL_YAW:
target.yaw += self.yaw
else:
target.yaw = self.yaw
if self.flags & self.FLAG_REL_PITCH:
target.pitch += self.pitch
else:
target.pitch = self.pitch
self.yaw %= 360
self.pitch %= 360
class DisconnectPacketPlayState(Packet):
get_id = staticmethod(lambda context:
0x1A if context.protocol_version >= 107 else
0x40)
@staticmethod
def get_id(context):
return 0x1A if context.protocol_version >= 107 else \
0x40
packet_name = "disconnect"
definition = [
@@ -360,32 +404,38 @@ class DisconnectPacketPlayState(Packet):
class SetCompressionPacketPlayState(Packet):
# Note: removed between protocol versions 47 and 107.
# Note: removed between protocol versions 47 and 107.
id = 0x46
packet_name = "set compression"
definition = [
{'threshold': VarInt}]
class PlayerListItemPacket(Packet):
get_id = staticmethod(lambda context:
0x2D if context.protocol_version >= 107 else
0x38)
@staticmethod
def get_id(context):
return 0x2D if context.protocol_version >= 107 else \
0x38
packet_name = "player list item"
class PlayerList(object):
__slots__ = 'players_by_uuid'
def __init__(self):
self.players_by_uuid = dict()
class PlayerListItem(object):
__slots__ = (
'uuid', 'name', 'properties', 'gamemode', 'ping', 'display_name')
def __init__(self, **kwds):
for key, val in kwds.items():
setattr(self, key, val)
class PlayerProperty(object):
__slots__ = 'name', 'value', 'signature'
__slots__ = 'name', 'value', 'signature'
def read(self, file_object):
self.name = String.read(file_object)
self.value = String.read(file_object)
@@ -397,6 +447,7 @@ class PlayerListItemPacket(Packet):
class Action(object):
__slots__ = 'uuid'
def read(self, file_object):
self.uuid = UUID.read(file_object)
self._read(file_object)
@@ -414,12 +465,14 @@ class PlayerListItemPacket(Packet):
3: PlayerListItemPacket.UpdateDisplayNameAction,
4: PlayerListItemPacket.RemovePlayerAction
}.get(action_id)
if subcls is None: raise ValueError(
"Unknown player list action ID: %s." % action_id)
if subcls is None:
raise ValueError("Unknown player list action ID: %s."
% action_id)
return subcls
class AddPlayerAction(Action):
__slots__ = 'name', 'properties', 'gamemode', 'ping', 'display_name'
def _read(self, file_object):
self.name = String.read(file_object)
prop_count = VarInt.read(file_object)
@@ -435,47 +488,58 @@ class PlayerListItemPacket(Packet):
self.display_name = String.read(file_object)
else:
self.display_name = None
def apply(self, player_list):
player = PlayerListItemPacket.PlayerListItem(
uuid = self.uuid,
name = self.name,
properties = self.properties,
gamemode = self.gamemode,
ping = self.ping,
display_name = self.display_name)
uuid=self.uuid,
name=self.name,
properties=self.properties,
gamemode=self.gamemode,
ping=self.ping,
display_name=self.display_name)
player_list.players_by_uuid[self.uuid] = player
class UpdateGameModeAction(Action):
__slots__ = 'gamemode'
def _read(self, file_object):
self.gamemode = VarInt.read(file_object)
def apply(self, player_list):
player = player_list.players_by_uuid.get(self.uuid)
if player: player.gamemode = self.gamemode
if player:
player.gamemode = self.gamemode
class UpdateLatencyAction(Action):
__slots__ = 'ping'
def _read(self, file_object):
self.ping = VarInt.read(file_object)
def apply(self, player_list):
player = player_list.players_by_uuid.get(self.uuid)
if player: player.ping = self.ping
if player:
player.ping = self.ping
class UpdateDisplayNameAction(Action):
__slots__ = 'display_name'
def _read(self, file_object):
has_display_name = Boolean.read(file_object)
if has_display_name:
self.display_name = String.read(file_object)
else:
self.display_name = None
def apply(self, player_list):
player = player_list.players_by_uuid.get(self.uuid)
if player: player.display_name = self.display_name
if player:
player.display_name = self.display_name
class RemovePlayerAction(Action):
def _read(self, file_object):
pass
def apply(self, player_list):
if self.uuid in player_list.players_by_uuid:
del player_list.players_by_uuid[self.uuid]
@@ -497,27 +561,34 @@ class PlayerListItemPacket(Packet):
def write(self, socket, compression_threshold=None):
raise NotImplementedError
class MapPacket(Packet):
get_id = staticmethod(lambda context:
0x24 if context.protocol_version >= 107 else
0x34)
@staticmethod
def get_id(context):
return 0x24 if context.protocol_version >= 107 else \
0x34
packet_name = 'map'
class MapIcon(object):
__slots__ = 'type', 'direction', 'location'
def __init__(self, type, direction, location):
self.type = type
self.direction = direction
self.location = location
def __repr__(self):
return ('MapIcon(type=%s, direction=%s, location=%s)'
% (self.type, self.direction, self.location))
% (self.type, self.direction, self.location))
def __str__(self):
return self.__repr__()
class Map(object):
__slots__ = ('id', 'scale', 'icons', 'pixels', 'width', 'height',
'is_tracking_position')
def __init__(self, id=None, scale=None, width=128, height=128):
self.id = id
self.scale = scale
@@ -526,18 +597,23 @@ class MapPacket(Packet):
self.height = height
self.pixels = bytearray(0 for i in range(width*height))
self.is_tracking_position = True
def __repr__(self):
return ('Map(id=%s, scale=%s, icons=%s, width=%s, height=%s)'
% (self.id, self.scale, self.icons, self.width, self.height))
return ('Map(id=%s, scale=%s, icons=%s, width=%s, height=%s)' % (
self.id, self.scale, self.icons, self.width, self.height))
def __str__(self):
return self.__repr__()
class MapSet(object):
__slots__ = 'maps_by_id'
def __init__(self):
self.maps_by_id = dict()
def __repr__(self):
return 'MapSet(%s)' % ', '.join(self.maps_by_id.values())
def __str__(self):
return self.__repr__()
@@ -580,7 +656,7 @@ class MapPacket(Packet):
z = self.offset[1] + i / self.width
map.pixels[x + map.width * z] = self.pixels[i]
map.is_tracking_position = self.is_tracking_position
def apply_to_map_set(self, map_set):
map = map_set.maps_by_id.get(self.map_id)
if map is None:
@@ -594,11 +670,13 @@ class MapPacket(Packet):
def __repr__(self):
return 'MapPacket(%s)' % ', '.join(
'%s=%r' % (k, v)
for (k,v) in self.__dict__.items()
for (k, v) in self.__dict__.items()
if k != 'pixels')
def __str__(self):
return self.__repr__()
def state_playing_clientbound(context):
packets = {
KeepAlivePacketClientbound,
@@ -609,25 +687,30 @@ def state_playing_clientbound(context):
PlayerListItemPacket,
DisconnectPacketPlayState,
}
if context.protocol_version <= 47: packets |= {
SetCompressionPacketPlayState,
}
if context.protocol_version <= 47:
packets |= {
SetCompressionPacketPlayState,
}
return packets
class ChatPacket(Packet):
get_id = staticmethod(lambda context:
0x02 if context.protocol_version >= 107 else
0x01)
@staticmethod
def get_id(context):
return 0x02 if context.protocol_version >= 107 else \
0x01
packet_name = "chat"
definition = [
{'message': String}]
class PositionAndLookPacket(Packet):
get_id = staticmethod(lambda context:
0x0D if context.protocol_version >= 107 else
0x06)
@staticmethod
def get_id(context):
return 0x0D if context.protocol_version >= 107 else \
0x06
packet_name = "position and look"
definition = [
{'x': Double},
@@ -637,6 +720,7 @@ class PositionAndLookPacket(Packet):
{'pitch': Float},
{'on_ground': Boolean}]
class TeleportConfirmPacket(Packet):
# Note: added between protocol versions 47 and 107.
id = 0x00
@@ -644,15 +728,19 @@ class TeleportConfirmPacket(Packet):
definition = [
{'teleport_id': VarInt}]
class AnimationPacketServerbound(Packet):
get_id = staticmethod(lambda context:
0x1A if context.protocol_version >= 107 else
0x0A)
@staticmethod
def get_id(context):
return 0x1A if context.protocol_version >= 107 else \
0x0A
packet_name = "animation"
get_definition = staticmethod(lambda context: [
{'hand': VarInt} if context.protocol_version >= 107 else {}])
HAND_MAIN = 0
HAND_OFF = 1
HAND_OFF = 1
def state_playing_serverbound(context):
packets = {
@@ -661,7 +749,8 @@ def state_playing_serverbound(context):
PositionAndLookPacket,
AnimationPacketServerbound,
}
if context.protocol_version >= 107: packets |= {
TeleportConfirmPacket,
}
if context.protocol_version >= 107:
packets |= {
TeleportConfirmPacket,
}
return packets
+1
View File
@@ -193,6 +193,7 @@ class String(Type):
VarInt.send(len(value), socket)
socket.send(value)
class UUID(Type):
@staticmethod
def read(file_object):