Moved code into a python module

This commit is contained in:
Jeppe Klitgaard committed 2015-04-01 17:19:12 +02:00
1 parent f9ab29880a
commit bb94d99bd4
8 files changed
+3 -6

No files matched your search

View File
Whitespace-only changes.
View File
Whitespace-only changes.
+106
View File
@@ -0,0 +1,106 @@
import urllib2
import json
#: The base url for Yggdrasil requests
BASE_URL = 'https://authserver.mojang.com/'
AGENT_INFO = {"name": "Minecraft", "version": 1}
class YggdrasilError(Exception):
"""Signals some sort of problem while handling a request to
the Yggdrasil service
:ivar human_error: A human readable description of the problem
:ivar error: A short description of the problem
"""
def __init__(self, error, human_readable_error):
self.error = error
self.human_readable_error = human_readable_error
def make_request(url, payload):
"""Makes an http request to the Yggdrasil authentication service
If there is an error then it will raise a :exc:`.YggdrasilError`
:param url: The fully formed url to the Yggdrasil endpoint, for example:
https://authserver.mojang.com/authenticate
You may use the :attr:`.BASE_URL` constant here as a shortcut
:param payload: The payload to send with the request, will be interpreted
as a JSON object so be careful.
Example: {"username": username, "password": password, "agent": AGENT_INFO}
:return: A :class:`.Response` object.
"""
response = Response()
try:
header = {'Content-Type': 'application/json'}
data = json.dumps(payload)
req = urllib2.Request(url, data, header)
opener = urllib2.build_opener()
http_response = opener.open(req, None, 10)
http_response = http_response.read()
except urllib2.HTTPError, e:
error = e.read()
error = json.loads(error)
response.human_error = error['errorMessage']
response.error = error['error']
raise YggdrasilError(error['error'], error['errorMessage'])
except urllib2.URLError, e:
raise YggdrasilError(e.reason, e.reason)
# ohey, everything didn't end up crashing and burning
if http_response == "":
http_response = "{}"
try:
json_response = json.loads(http_response)
except ValueError, e:
raise YggdrasilError(e.message, "JSON parsing exception on data: " + http_response)
response.payload = json_response
return response
class Response(object):
"""Class to hold responses from Yggdrasil
:ivar payload: The raw payload returned by Yggdrasil
"""
payload = None
class LoginResponse(object):
"""A container class to hold information received from Yggdrasil
upon logging into an account.
:ivar username: The actual in game username of the user
:ivar access_token: The access token of the user, used in place of the password
:ivar profile_id: The selected profile id
"""
pass
def login_to_minecraft(username, password):
"""
Logs in to a minecraft account
Will raise a :exc:`.YggdrasilError` on failure
:param username: The mojang account username
:param password: The password for the account
:return: A :class:`.LoginResponse` object
"""
payload = {"username": username, "password": password, "agent": AGENT_INFO}
response = make_request(BASE_URL + "authenticate", payload)
login_response = LoginResponse()
payload = response.payload
login_response.access_token = payload["accessToken"]
login_response.profile_id = payload["selectedProfile"]["id"]
login_response.username = payload["selectedProfile"]["name"]
return login_response
+328
View File
@@ -0,0 +1,328 @@
from collections import deque
from threading import Lock
from zlib import decompress
import threading
import socket
import time
import select
import authentication
from packets import *
from types import VarInt
PROTOCOL_VERSION = 47
class ConnectionOptions(object):
# TODO: allow these options to be overriden from a constructor below
address = None
port = None
use_encryption = True
compression_threshold = -1
compression_enabled = False
class Connection(object):
"""This class represents a connection to a minecraft
server, it handles everything from connecting, sending packets to
handling default network behaviour
"""
_outgoing_packet_queue = deque()
_write_lock = Lock()
networking_thread = None
options = ConnectionOptions()
packet_listeners = []
# The reactor handles all the default responses to packets,
# it should be changed per networking state
reactor = None
#: Indicates if this connection is spawned in the Minecraft game world
spawned = False
def __init__(self, address, port, login_response):
"""Sets up an instance of this object to be able to connect to a minecraft server.
The connect method needs to be called in order to actually begin the connection
:param address: address of the server to connect to
:param port(int): port of the server to connect to
:param login_response: :class:`authentication.LoginResponse` object as obtained from the authentication package
"""
self.options.address = address
self.options.port = port
self.login_response = login_response
self.reactor = PacketReactor(self)
def _start_network_thread(self):
self.networking_thread = NetworkingThread(self)
self.networking_thread.start()
def write_packet(self, packet, force=False):
"""Writes a packet to the server.
If force is set to true, the method attempts to acquire the write lock and write the packet
out immediately, and as such may block.
If force is false then the packet will be added to the end of the packet writing queue
to be sent 'as soon as possible'
:param packet: The :class:`network.packets.Packet` to write
:param force(bool): Specifies if the packet write should be immediate
"""
if force:
self._write_lock.acquire()
if self.options.compression_enabled:
packet.write(self.socket, self.options.compression_threshold)
else:
packet.write(self.socket)
self._write_lock.release()
else:
self._outgoing_packet_queue.append(packet)
def register_packet_listener(self, method, *args):
"""
Registers a listener method which will be notified when a packet of
a selected type is received
:param method: The method which will be called back with the packet
:param args: The packets to listen for
"""
self.packet_listeners.append(PacketListener(method, *args))
def _pop_packet(self):
# Pops the topmost packet off the outgoing queue and writes it out through the socket
#
# Mostly an internal 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
if len(self._outgoing_packet_queue) == 0:
return False
else:
packet = self._outgoing_packet_queue.popleft()
if self.options.compression_enabled:
packet.write(self.socket, self.options.compression_threshold)
else:
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):
"""Attempt to begin connecting to the server
"""
self._connect()
self._handshake()
self.reactor = LoginReactor(self)
self._start_network_thread()
login_start_packet = LoginStartPacket()
login_start_packet.name = self.login_response.username
self.write_packet(login_start_packet)
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.connect((self.options.address, self.options.port))
self.file_object = self.socket.makefile()
def _handshake(self, next_state=2):
handshake = HandShakePacket()
handshake.protocol_version = PROTOCOL_VERSION
handshake.server_address = self.options.address
handshake.server_port = self.options.port
handshake.next_state = next_state
self.write_packet(handshake)
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():
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.file_object)
while packet:
num_packets += 1
self.connection.reactor.react(packet)
for listener in self.connection.packet_listeners:
listener.call_packet(packet)
if num_packets >= 50:
break
packet = self.connection.reactor.read_packet(self.connection.file_object)
time.sleep(0.05)
class PacketReactor(object):
"""
Reads and reacts to packets
"""
state_name = None
clientbound_packets = None
TIME_OUT = 1
def __init__(self, connection):
self.connection = connection
def read_packet(self, stream):
ready_to_read, _, __ = select.select([self.connection.socket], [], [], self.TIME_OUT)
if self.connection.socket in ready_to_read:
length = VarInt.read_socket(self.connection.socket)
packet_data = PacketBuffer()
packet_data.send(stream.read(length))
# Ensure we read all the packet
while len(packet_data.get_writable()) < length:
packet_data.send(stream.read(length - len(packet_data.get_writable())))
packet_data.reset_cursor()
if self.connection.options.compression_enabled:
compressed_size = VarInt.read(packet_data)
if compressed_size > 0:
decompressed_packet = decompress(packet_data.read(compressed_size))
packet_data.reset()
packet_data.send(decompressed_packet)
packet_data.reset_cursor()
packet_id = VarInt.read(packet_data)
# If we know the structure of the packet, attempt to parse it
# otherwise just skip it
if packet_id in self.clientbound_packets:
packet = self.clientbound_packets[packet_id]()
packet.read(packet_data)
return packet
else:
return Packet()
else:
return None
def react(self, packet):
raise NotImplementedError("Call to base reactor")
class LoginReactor(PacketReactor):
clientbound_packets = state_login_clientbound
def react(self, packet):
# TODO: Add some way to bypass encryption? (connection.options.use_encryption) Not sure if it's still possible.
if packet.packet_name == "encryption request":
import encryption
secret = encryption.generate_shared_secret()
encrypted_token, encrypted_secret = encryption.encrypt_token_and_secret(packet.public_key,
packet.verify_token, secret)
# A server id of '-' means the server is in offline mode
if packet.server_id != '-':
url = "https://sessionserver.mojang.com/session/minecraft/join"
server_id = encryption.generate_verification_hash(packet.server_id, secret, packet.public_key)
payload = {'accessToken': self.connection.login_response.access_token,
'selectedProfile': self.connection.login_response.profile_id,
'serverId': server_id}
authentication.make_request(url, payload)
encryption_response = EncryptionResponsePacket()
encryption_response.shared_secret = encrypted_secret
encryption_response.verify_token = encrypted_token
# Forced because we don't want to send this encrypted which it will be
# if we put it in the queue as we'd have wrapped the socket and file object by then
self.connection.write_packet(encryption_response, force=True)
# Enable the encryption
cipher = encryption.create_AES_cipher(secret)
encryptor = cipher.encryptor()
decryptor = cipher.decryptor()
self.connection.socket = encryption.EncryptedSocketWrapper(self.connection.socket,
encryptor, decryptor)
self.connection.file_object = encryption.EncryptedFileObjectWrapper(self.connection.file_object,
decryptor)
if packet.packet_name == "disconnect":
print(packet.json_data) # TODO: handle propagating this back
if packet.packet_name == "login success":
self.connection.reactor = PlayingReactor(self.connection)
if packet.packet_name == "set compression":
self.connection.options.compression_threshold = packet.threshold
self.connection.options.compression_enabled = True
class PlayingReactor(PacketReactor):
clientbound_packets = state_playing_clientbound
def react(self, packet):
if packet.packet_name == "set compression":
self.connection.options.compression_threshold = packet.threshold
self.connection.options.compression_enabled = True
if packet.packet_name == "keep alive":
keep_alive_packet = KeepAlivePacket()
keep_alive_packet.keep_alive_id = packet.keep_alive_id
self.connection.write_packet(keep_alive_packet)
if packet.packet_name == "player position and look":
position_response = PositionAndLookPacket()
position_response.x = packet.x
position_response.feet_y = packet.y
position_response.z = packet.z
position_response.yaw = packet.yaw
position_response.pitch = packet.pitch
position_response.on_ground = True
self.connection.write_packet(position_response)
self.connection.spawned = True
if packet.packet_name == "disconnect":
print(packet.json_data) # TODO: handle propagating this back
class StatusReactor(PacketReactor):
clientbound_packets = state_status_clientbound
def react(self, packet):
if packet.id == ResponsePacket.id:
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
+81
View File
@@ -0,0 +1,81 @@
import os
from hashlib import sha1
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15
from cryptography.hazmat.primitives.serialization import load_der_public_key
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
def generate_shared_secret():
return os.urandom(16)
def create_AES_cipher(shared_secret):
cipher = Cipher(algorithms.AES(shared_secret), modes.CFB8(shared_secret), backend=default_backend())
return cipher
def encrypt_token_and_secret(pubkey, verification_token, shared_secret):
"""Encrypts the verification token and shared secret with the server's public key
:param pubkey: The RSA public key provided by the server
:param verification_token: The verification token provided by the server
:param shared_secret: The generated shared secret
:return: A tuple containing (encrypted token, encrypted secret)
"""
pubkey = load_der_public_key(pubkey, default_backend())
if not isinstance(pubkey, rsa.RSAPublicKey):
raise RuntimeError("Public key provided by server not an RSA key")
encrypted_token = pubkey.encrypt(verification_token, PKCS1v15())
encrypted_secret = pubkey.encrypt(shared_secret, PKCS1v15())
return encrypted_token, encrypted_secret
def generate_verification_hash(server_id, shared_secret, public_key):
verification_hash = sha1()
verification_hash.update(server_id)
verification_hash.update(shared_secret)
verification_hash.update(public_key)
# Minecraft first parses the sha1 bytes as a signed number and then spits outs
# its hex representation
number = _number_from_bytes(verification_hash.digest(), signed=True)
return format(number, 'x')
def _number_from_bytes(b, signed=False):
if len(b) == 0:
b = b'\x00'
num = int(str(b).encode('hex'), 16)
if signed and (ord(b[0]) & 0x80):
num -= 2 ** (len(b) * 8)
return num
class EncryptedFileObjectWrapper(object):
def __init__(self, file_object, decryptor):
self.actual_file_object = file_object
self.decryptor = decryptor
def read(self, length):
return self.decryptor.update(self.actual_file_object.read(length))
class EncryptedSocketWrapper(object):
def __init__(self, socket, encryptor, decryptor):
self.actual_socket = socket
self.encryptor = encryptor
self.decryptor = decryptor
def recv(self, length):
return self.decryptor.update(self.actual_socket.recv(length))
def send(self, data):
self.actual_socket.send(self.encryptor.update(data))
def fileno(self):
return self.actual_socket.fileno()
+302
View File
@@ -0,0 +1,302 @@
from io import BytesIO
from zlib import compress
from types import *
class PacketBuffer(object):
def __init__(self):
self.b = BytesIO()
def send(self, value):
"""
Writes the given bytes to the buffer, designed to emulate socket.send
:param value: The bytes to write
"""
self.b.write(value)
def read(self, length):
return self.b.read(length)
def reset(self):
self.b = BytesIO()
def reset_cursor(self):
self.b.seek(0)
def get_writable(self):
return self.b.getvalue()
class PacketListener(object):
packets_to_listen = []
def __init__(self, callback, *args):
self.callback = callback
for arg in args:
if issubclass(arg, Packet):
self.packets_to_listen.append(arg)
def call_packet(self, packet):
for packet_type in self.packets_to_listen:
if isinstance(packet, packet_type):
self.callback(packet)
class Packet(object):
packet_name = "base"
id = -0x01
definition = []
def __init__(self):
pass
def read(self, file_object):
for field in self.definition:
for var_name, data_type in field.iteritems():
value = data_type.read(file_object)
setattr(self, var_name, value)
def write(self, socket, compression_threshold=-1):
# buffer the data since we need to know the length of each packet's payload
packet_buffer = PacketBuffer()
# write packet's id right off the bat in the header
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)
# compression_threshold of -1 means compression is disabled
if compression_threshold != -1:
if len(packet_buffer.get_writable()) > compression_threshold:
# compress the current payload
compressed_data = compress(packet_buffer.get_writable())
packet_buffer.reset()
# write out the length of the compressed payload
VarInt.send(len(compressed_data), packet_buffer)
# write the compressed payload itself
packet_buffer.send(compressed_data)
else:
# write out a 0 to indicate uncompressed data
packet_buffer.reset()
VarInt.send(0, 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
packet_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
packet_name = "response"
definition = [
{'json_response': String}]
class PingPacket(Packet):
id = 0x01
packet_name = "ping"
definition = [
{'time': Long}]
state_status_clientbound = {
0x00: ResponsePacket,
0x01: PingPacket
}
class RequestPacket(Packet):
id = 0x00
packet_name = "request"
definition = []
class PingPacket(Packet):
id = 0x01
packet_name = "ping"
definition = [
{'time': Long}]
state_status_serverbound = {
0x00: RequestPacket,
0x01: PingPacket
}
# Login State
# ==============
class DisconnectPacket(Packet):
id = 0x00
packet_name = "disconnect"
definition = [
{'json_data': String}]
class EncryptionRequestPacket(Packet):
id = 0x01
packet_name = "encryption request"
definition = [
{'server_id': String},
{'public_key': VarIntPrefixedByteArray},
{'verify_token': VarIntPrefixedByteArray}]
class LoginSuccessPacket(Packet):
id = 0x02
packet_name = "login success"
definition = [
{'UUID': String},
{'Username': String}]
class SetCompressionPacket(Packet):
id = 0x03
packet_name = "set compression"
definition = [
{'threshold': VarInt}]
state_login_clientbound = {
0x00: DisconnectPacket,
0x01: EncryptionRequestPacket,
0x02: LoginSuccessPacket,
0x03: SetCompressionPacket
}
class LoginStartPacket(Packet):
id = 0x00
packet_name = "login start"
definition = [
{'name': String}]
class EncryptionResponsePacket(Packet):
id = 0x01
packet_name = "encryption response"
definition = [
{'shared_secret': VarIntPrefixedByteArray},
{'verify_token': VarIntPrefixedByteArray}]
state_login_serverbound = {
0x00: LoginStartPacket,
0x01: EncryptionResponsePacket
}
# Playing State
# ==============
class KeepAlivePacket(Packet):
id = 0x00
packet_name = "keep alive"
definition = [
{'keep_alive_id': VarInt}]
class JoinGamePacket(Packet):
id = 0x01
packet_name = "join game"
definition = [
{'entity_id': Integer},
{'game_mode': UnsignedByte},
{'dimension': Byte},
{'difficulty': UnsignedByte},
{'max_players': UnsignedByte},
{'level_type': String},
{'reduced_debug_info': Boolean}]
class ChatMessagePacket(Packet):
id = 0x02
packet_name = "chat message"
definition = [
{'json_data': String},
{'position': Byte}]
class PlayerPositionAndLookPacket(Packet):
id = 0x08
packet_name = "player position and look"
definition = [
{'x': Double},
{'y': Double},
{'z': Double},
{'yaw': Float},
{'pitch': Float},
{'flags': Byte}]
class DisconnectPacketPlayState(Packet):
id = 0x40
packet_name = "disconnect"
definition = [
{'json_data': String}]
class SetCompressionPacketPlayState(Packet):
id = 0x46
packet_name = "set compression"
definition = [
{'threshold': VarInt}]
state_playing_clientbound = {
0x00: KeepAlivePacket,
0x01: JoinGamePacket,
0x02: ChatMessagePacket,
0x08: PlayerPositionAndLookPacket,
0x40: DisconnectPacketPlayState,
0x46: SetCompressionPacketPlayState
}
class ChatPacket(Packet):
id = 0x01
packet_name = "chat"
definition = [
{'message': String}]
class PositionAndLookPacket(Packet):
id = 0x06
packet_name = "position and look"
definition = [
{'x': Double},
{'feet_y': Double},
{'z': Double},
{'yaw': Float},
{'pitch': Float},
{'on_ground': Boolean}]
state_playing_serverbound = {
0x00: KeepAlivePacket,
0x01: ChatPacket,
0x06: PositionAndLookPacket
}
+205
View File
@@ -0,0 +1,205 @@
"""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(object):
@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 UnsignedByte(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 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 = s.recv(1)
if b == "":
raise RuntimeError("Socket disconnected")
b = ord(b)
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)
@staticmethod
def size(value):
for max_value, size in VarInt_size_table.iteritems():
if value < max_value:
return size
# Maps (maximum integer value -> size of VarInt in bytes)
VarInt_size_table = {
2**7: 1,
2**14: 2,
2**21: 3,
2**28: 4,
2**35: 5,
2**42: 6,
2**49: 7,
2**56: 8,
2**63: 9,
2**70: 10,
2**77: 11,
2**84: 12
}
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(value, 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 ShortPrefixedByteArray(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 VarIntPrefixedByteArray(Type):
@staticmethod
def read(file_object, length=None):
if length is None:
length = VarInt.read(file_object)
return struct.unpack(str(length) + "s", file_object.read(length))[0]
@staticmethod
def send(value, socket):
VarInt.send(len(value), socket)
socket.send(struct.pack(str(len(value)) + "s", 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)