Lay down the foundations for a complete rewrite, the new framework is far more easy to maintain
This commit is contained in:
1 parent
59e4706b25
commit
85112fba1d
17 files changed
+607
-2135
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,173 @@
|
||||
from packets import *
|
||||
from start import PROTOCOL_VERSION
|
||||
from collections import deque
|
||||
from threading import Lock
|
||||
from types import VarInt
|
||||
import threading
|
||||
import socket
|
||||
import time
|
||||
import select
|
||||
|
||||
|
||||
class Connection:
|
||||
"""This class represents a connection to a minecraft
|
||||
server, it handles everything from connecting, sending packets,
|
||||
handling default network behaviour
|
||||
"""
|
||||
outgoing_packet_queue = deque()
|
||||
write_lock = Lock()
|
||||
networking_thread = None
|
||||
|
||||
def __init__(self, address, port, login_response):
|
||||
self.address = address
|
||||
self.port = port
|
||||
self.login_response = login_response
|
||||
self.reactor = HandshakeReactor(self)
|
||||
|
||||
def _start_network_thread(self):
|
||||
self.networking_thread = NetworkingThread(self)
|
||||
self.networking_thread.start()
|
||||
|
||||
def write_packet(self, packet, force=False):
|
||||
if force:
|
||||
self.write_lock.acquire()
|
||||
packet.write(self.socket)
|
||||
self.write_lock.release()
|
||||
else:
|
||||
self.outgoing_packet_queue.append(packet)
|
||||
|
||||
# Mostly a convenience function, caller should make sure they have the
|
||||
# write lock acquired to avoid issues caused by asynchronous access to the socket.
|
||||
# This should be the only method that removes elements from the outbound queue
|
||||
def _pop_packet(self):
|
||||
if len(self.outgoing_packet_queue) == 0:
|
||||
return False
|
||||
else:
|
||||
packet = self.outgoing_packet_queue.popleft()
|
||||
print "Writing out: " + hex(packet.id) + " / " + packet.name
|
||||
packet.write(self.socket)
|
||||
return True
|
||||
|
||||
def status(self):
|
||||
self._connect()
|
||||
self._handshake(1)
|
||||
self._start_network_thread()
|
||||
self.reactor = StatusReactor(self)
|
||||
|
||||
request_packet = RequestPacket()
|
||||
self.write_packet(request_packet)
|
||||
|
||||
def connect(self):
|
||||
self._connect()
|
||||
self._handshake()
|
||||
|
||||
def _connect(self):
|
||||
#Connect a socket to the server and create a file object from the socket
|
||||
#The file object is used to read any and all data from the socket since it's "guaranteed"
|
||||
#to read the number of bytes specified, the socket itself will mostly be
|
||||
#used to write data upstream to the server
|
||||
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
self.socket.settimeout(20.0)
|
||||
self.socket.connect(( self.address, self.port ))
|
||||
self.file_object = self.socket.makefile()
|
||||
|
||||
def _handshake(self, next_state=2):
|
||||
handshake = HandShakePacket()
|
||||
handshake.protocol_version = PROTOCOL_VERSION
|
||||
handshake.server_address = self.address
|
||||
handshake.server_port = self.port
|
||||
handshake.next_state = next_state
|
||||
|
||||
handshake.write(self.socket)
|
||||
|
||||
|
||||
class NetworkingThread(threading.Thread):
|
||||
interrupt = False
|
||||
|
||||
def __init__(self, connection):
|
||||
threading.Thread.__init__(self)
|
||||
self.connection = connection
|
||||
self.name = "Networking Thread"
|
||||
self.daemon = True
|
||||
|
||||
def run(self):
|
||||
while True:
|
||||
if self.interrupt:
|
||||
break
|
||||
# Attempt to write out as many as 300 packets as possible every 0.05 seconds (20 ticks per second)
|
||||
num_packets = 0
|
||||
self.connection.write_lock.acquire()
|
||||
while self.connection._pop_packet():
|
||||
|
||||
self.connection._pop_packet()
|
||||
|
||||
num_packets += 1
|
||||
if num_packets >= 300:
|
||||
break
|
||||
self.connection.write_lock.release()
|
||||
|
||||
# Read and react to as many as 50 packets
|
||||
num_packets = 0
|
||||
packet = self.connection.reactor.read_packet(self.connection.socket, self.connection.file_object)
|
||||
while packet:
|
||||
num_packets += 1
|
||||
|
||||
self.connection.reactor.react(packet)
|
||||
if num_packets >= 50:
|
||||
break
|
||||
|
||||
packet = self.connection.reactor.read_packet(self.connection.socket, self.connection.file_object)
|
||||
|
||||
time.sleep(0.05)
|
||||
|
||||
|
||||
class PacketReactor:
|
||||
|
||||
state_name = None
|
||||
clientbound_packets = None
|
||||
|
||||
TIME_OUT = 0.5
|
||||
|
||||
def __init__(self, connection):
|
||||
self.connection = connection
|
||||
|
||||
def read_packet(self, socket, stream):
|
||||
ready = select.select([self.connection.socket], [], [], 0.5)
|
||||
if ready[0]:
|
||||
length = VarInt.read(stream)
|
||||
packet_id = VarInt.read(stream)
|
||||
|
||||
if packet_id in self.clientbound_packets:
|
||||
packet = self.clientbound_packets[packet_id]()
|
||||
packet.read(stream)
|
||||
return packet
|
||||
else:
|
||||
print "Unkown packet: " + str(packet_id) + " / " + hex(packet_id)
|
||||
return Packet()
|
||||
else:
|
||||
return None
|
||||
|
||||
def react(self, packet):
|
||||
pass
|
||||
|
||||
|
||||
class HandshakeReactor(PacketReactor):
|
||||
|
||||
clientbound_packets = state_handshake_clientbound
|
||||
|
||||
|
||||
class StatusReactor(PacketReactor):
|
||||
|
||||
clientbound_packets = state_status_clientbound
|
||||
|
||||
def react(self, packet):
|
||||
if packet.name == "response":
|
||||
import json
|
||||
print json.loads(packet.json_response)
|
||||
|
||||
ping_packet = PingPacket()
|
||||
ping_packet.time = int(time.time())
|
||||
self.connection.write_packet(ping_packet)
|
||||
|
||||
self.connection.networking_thread.interrupt = True
|
||||
# TODO: More shutdown? idk
|
||||
@@ -0,0 +1,143 @@
|
||||
from types import *
|
||||
from io import BytesIO
|
||||
|
||||
|
||||
class PacketBuffer:
|
||||
b = BytesIO()
|
||||
|
||||
def send(self, value):
|
||||
self.b.write(value)
|
||||
|
||||
def get_writable(self):
|
||||
return self.b.getvalue()
|
||||
|
||||
class Packet:
|
||||
|
||||
name = "base"
|
||||
definition = []
|
||||
|
||||
def read(self, file_object):
|
||||
for field in self.definition:
|
||||
for var_name, data_type in field.iteritems():
|
||||
setattr(self, var_name, data_type.read(file_object))
|
||||
|
||||
def write(self, socket):
|
||||
# buffer the data since we need to know the length of each packet's payload
|
||||
packet_buffer = PacketBuffer()
|
||||
# write off the id right off the bat
|
||||
VarInt.send(self.id, packet_buffer)
|
||||
|
||||
for field in self.definition:
|
||||
for var_name, data_type in field.iteritems():
|
||||
data = getattr(self, var_name)
|
||||
data_type.send(data, packet_buffer)
|
||||
|
||||
VarInt.send(len(packet_buffer.get_writable()), socket) # Packet Size
|
||||
socket.send(packet_buffer.get_writable()) # Packet Payload
|
||||
|
||||
|
||||
# Handshake State
|
||||
#==============
|
||||
class HandShakePacket(Packet):
|
||||
|
||||
id = 0x00
|
||||
name = "handshake"
|
||||
definition = [
|
||||
{'protocol_version': VarInt},
|
||||
{'server_address': String},
|
||||
{'server_port': UnsignedShort},
|
||||
{'next_state': VarInt}]
|
||||
|
||||
state_handshake_clientbound = {
|
||||
|
||||
}
|
||||
state_handshake_serverbound = {
|
||||
0x00: HandShakePacket
|
||||
}
|
||||
|
||||
# Status State
|
||||
#==============
|
||||
class ResponsePacket(Packet):
|
||||
id = 0x00
|
||||
name = "response"
|
||||
definition = [
|
||||
{'json_response': String}]
|
||||
|
||||
class PingPacket(Packet):
|
||||
id = 0x01
|
||||
name = "ping"
|
||||
definition = [
|
||||
{'time': Long}]
|
||||
|
||||
state_status_clientbound = {
|
||||
0x00: ResponsePacket,
|
||||
0x01: PingPacket
|
||||
}
|
||||
|
||||
class RequestPacket(Packet):
|
||||
id = 0x00
|
||||
name = "request"
|
||||
definition = []
|
||||
|
||||
class PingPacket(Packet):
|
||||
id = 0x01
|
||||
name = "ping"
|
||||
definition = [
|
||||
{'time': Long}]
|
||||
|
||||
state_status_serverbound = {
|
||||
0x00: RequestPacket,
|
||||
0x01: PingPacket
|
||||
}
|
||||
|
||||
# Login State
|
||||
#==============
|
||||
class DisconnectPacket(Packet):
|
||||
|
||||
id = 0x00
|
||||
name = "disconnect"
|
||||
definition = [
|
||||
{'json_data': String}]
|
||||
|
||||
class EncryptionRequestPacket(Packet):
|
||||
|
||||
id = 0x01
|
||||
name = "encryption request"
|
||||
definition = [
|
||||
{'server_id': String},
|
||||
{'public_key': ByteArray},
|
||||
{'verify_token': ByteArray}]
|
||||
|
||||
class LoginSucessPacket(Packet):
|
||||
|
||||
id = 0x02
|
||||
name = "login success"
|
||||
definition = [
|
||||
{'UUID': String},
|
||||
{'Username': String}]
|
||||
|
||||
state_login_clientbound = {
|
||||
0x00: DisconnectPacket,
|
||||
0x01: EncryptionRequestPacket,
|
||||
0x02: LoginSucessPacket
|
||||
}
|
||||
|
||||
class LoginStartPacket(Packet):
|
||||
|
||||
id = 0x00
|
||||
name = "login start"
|
||||
definition = [
|
||||
{'name': String}]
|
||||
|
||||
class EncryptionResponsePacket(Packet):
|
||||
|
||||
id = 0x01
|
||||
name = "encryption response"
|
||||
definition = [
|
||||
{'shared_secret': ByteArray},
|
||||
{'verify_token': ByteArray}]
|
||||
|
||||
state_login_serverbound = {
|
||||
0x00: LoginStartPacket,
|
||||
0x01: EncryptionResponsePacket
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
"""Contains definitions for minecraft's different data types
|
||||
Each type has a method which is used to read and write it.
|
||||
These definitions and methods are used by the packet definitions
|
||||
"""
|
||||
import struct
|
||||
|
||||
class Type:
|
||||
|
||||
@staticmethod
|
||||
def read(file_object):
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def send(value, socket):
|
||||
pass
|
||||
|
||||
#=========================================================
|
||||
|
||||
|
||||
class Boolean(Type):
|
||||
|
||||
@staticmethod
|
||||
def read(file_object):
|
||||
return struct.unpack('?', file_object.read(1))[0]
|
||||
|
||||
@staticmethod
|
||||
def send(value, socket):
|
||||
socket.send(struct.pack('?', value))
|
||||
|
||||
|
||||
class Byte(Type):
|
||||
|
||||
@staticmethod
|
||||
def read(file_object):
|
||||
return struct.unpack('>b', file_object.read(1))[0]
|
||||
|
||||
@staticmethod
|
||||
def send(value, socket):
|
||||
socket.send(struct.pack('>b', value))
|
||||
|
||||
|
||||
class Short(Type):
|
||||
|
||||
@staticmethod
|
||||
def read(file_object):
|
||||
return struct.unpack('>h', file_object.read(2))[0]
|
||||
|
||||
@staticmethod
|
||||
def send(value, socket):
|
||||
socket.send(struct.pack('>h', value))
|
||||
|
||||
|
||||
class UnsignedShort(Type):
|
||||
|
||||
@staticmethod
|
||||
def read(file_object):
|
||||
return struct.unpack('>H', file_object.read(2))[0]
|
||||
|
||||
@staticmethod
|
||||
def send(value, socket):
|
||||
socket.send(struct.pack('>H', value))
|
||||
|
||||
|
||||
class Integer(Type):
|
||||
|
||||
@staticmethod
|
||||
def read(file_object):
|
||||
return struct.unpack('>i', file_object.read(4))[0]
|
||||
|
||||
@staticmethod
|
||||
def send(value, socket):
|
||||
socket.send(struct.pack('>i', value))
|
||||
|
||||
|
||||
class VarInt(Type):
|
||||
|
||||
@staticmethod
|
||||
def read_socket(s):
|
||||
d = 0
|
||||
for i in range(5):
|
||||
b = ord(s.recv(1))
|
||||
d |= (b & 0x7F) << 7 * i
|
||||
if not b & 0x80:
|
||||
break
|
||||
return d
|
||||
|
||||
@staticmethod
|
||||
def read(file_object):
|
||||
d = 0
|
||||
for i in range(5):
|
||||
b = ord(file_object.read(1))
|
||||
d |= (b & 0x7F) << 7 * i
|
||||
if not b & 0x80:
|
||||
break
|
||||
return d
|
||||
|
||||
@staticmethod
|
||||
def send(value, socket):
|
||||
o = ""
|
||||
while True:
|
||||
b = value & 0x7F
|
||||
value >>= 7
|
||||
o += struct.pack("B", b | (0x80 if value > 0 else 0))
|
||||
if value == 0:
|
||||
break
|
||||
socket.send(o)
|
||||
|
||||
|
||||
class Long(Type):
|
||||
|
||||
@staticmethod
|
||||
def read(file_object):
|
||||
return struct.unpack('>q', file_object.read(8))[0]
|
||||
|
||||
@staticmethod
|
||||
def send(value, socket):
|
||||
socket.send(struct.pack('>q', value))
|
||||
|
||||
|
||||
class Float(Type):
|
||||
|
||||
@staticmethod
|
||||
def read(file_object):
|
||||
return struct.unpack('>f', file_object.read(4))[0]
|
||||
|
||||
@staticmethod
|
||||
def send(svalue, socket):
|
||||
socket.send(struct.pack('>f', value))
|
||||
|
||||
class Double(Type):
|
||||
|
||||
@staticmethod
|
||||
def read(file_object):
|
||||
return struct.unpack('>d', file_object.read(8))[0]
|
||||
|
||||
@staticmethod
|
||||
def send(value, socket):
|
||||
socket.send(struct.pack('>d', value))
|
||||
|
||||
|
||||
class ByteArray(Type):
|
||||
|
||||
@staticmethod
|
||||
def read(file_object, length=None):
|
||||
if length is None:
|
||||
length = Short.read(file_object)
|
||||
return struct.unpack(str(length) + "s", file_object.read(length))[0]
|
||||
|
||||
@staticmethod
|
||||
def send(value, socket):
|
||||
Short.send(len(value), socket)
|
||||
socket.send(value)
|
||||
|
||||
|
||||
class String(Type):
|
||||
|
||||
@staticmethod
|
||||
def read(file_object):
|
||||
length = VarInt.read(file_object)
|
||||
return unicode(file_object.read(length), "utf-8")
|
||||
|
||||
@staticmethod
|
||||
def send(value, socket):
|
||||
value = unicode(value).encode('utf-8')
|
||||
VarInt.send(len(value), socket)
|
||||
socket.send(value)
|
||||
Reference in new issue
Block a user