Source

txMysql / txmysql / packet.py

Full commit
"""
Includes format strings that describe packets
and classes to read/write packets.

"""


import struct

# packers
def pack_uint8(x):
    bytes = struct.pack("B", x)
    return bytes

def pack_uint24(x):
    bytes = struct.pack("BBB", x&0xFF, (x>>8)&0xFF, (x>>16)&0xFF)
    return bytes

def packHeader(length, order):
    return pack_uint24(length) + pack_uint8(order)

# unpackers
def unpack_uint8(byte):
    return struct.unpack("B", byte)[0]

def unpack_uint24(bytes):
    return ((struct.unpack("B", bytes[0])[0]) +
            (struct.unpack("B", bytes[1])[0]<<8) +
            (struct.unpack("B", bytes[2])[0]<<16))

def unpackHeader(bytes):
    return (unpack_uint24(bytes[0:3]),
            unpack_uint8(bytes[3]))


# Packet Class
class Packet(object):
    def __init__(self, bytes):
        self.length, self.order = unpackHeader(bytes[0:4])
        self.bytes = bytes[4:]


handshakeInitializationFormat = "B%ssL8sxHBHx13s"


def packHandshakeInitialization(protocolVersion,
                                serverVersion,
                                threadId,
                                scrambleBuffer,
                                serverCapabilities,
                                serverLanguage,
                                serverStatus,
                                restOfScramble):
    bytes = ""
    bytes += struct.pack(handshakeInitializationFormat % (
            len(serverVersion),
            ),
                         protocolVersion,
                         serverVersion,
                         threadId,
                         scrambleBuffer,
                         serverCapabilities,
                         serverLanguage,
                         serverStatus,
                         restOfScramble)
    return bytes


def unpackHandshakeInitialization(bytes):
    index = bytes.find("\0")
    values = struct.unpack(handshakeInitializationFormat % (index-1,), bytes)
    return values


class HandshakeInitializationPacket(Packet):
    def __init__(self, bytes):
        super(HandshakeInitializationPacket, self).__init__(self)
        handshakeValues = unpackHandshakeInitialization(self.bytes)