import struct import logging from collections import namedtuple from typing import Dict, List, Optional logger = logging.getLogger(__name__) PROTOCOL18_SIGNAL = 0xF3 # Photon command types inside an eNet envelope CMD_SEND_RELIABLE = 0x06 CMD_SEND_UNRELIABLE = 0x07 CMD_SEND_FRAGMENT = 0x08 CMD_SEND_UNRELIABLE_FRAGMENT = 0x0B CMD_ACKNOWLEDGE = 0x03 CMD_PING = 0x05 CMD_LOGOUT = 0x04 # Photon message types MSG_OPERATION_REQUEST = 0x02 MSG_OPERATION_RESPONSE = 0x03 MSG_EVENT_DATA = 0x04 MSG_INTERNAL_REQUEST = 0x06 MSG_INTERNAL_RESPONSE = 0x07 P18 = { 'Boolean': 2, 'Byte': 3, 'Short': 4, 'Float': 5, 'Double': 6, 'String': 7, 'Null': 8, 'CompressedInt': 9, 'CompressedLong': 10, 'Int1': 11, 'Int1Neg': 12, 'Int2': 13, 'Int2Neg': 14, 'Long1': 15, 'Long1Neg': 16, 'Long2': 17, 'Long2Neg': 18, 'Custom': 19, 'Dictionary': 20, 'Hashtable': 21, 'ObjectArray': 23, 'OperationRequest': 24, 'OperationResponse': 25, 'EventData': 26, 'BooleanFalse': 27, 'BooleanTrue': 28, 'ShortZero': 29, 'IntZero': 30, 'LongZero': 31, 'FloatZero': 32, 'DoubleZero': 33, 'ByteZero': 34, 'Array': 64, 'BooleanArray': 66, 'ByteArray': 67, 'ShortArray': 68, 'FloatArray': 69, 'DoubleArray': 70, 'StringArray': 71, 'CompressedIntArray': 73, 'CompressedLongArray': 74, 'CustomTypeArray': 83, 'DictionaryArray': 84, 'HashtableArray': 85, 'CustomTypeSlim': 128, } PhotonMessage = namedtuple( 'PhotonMessage', ('kind', 'code', 'params', 'return_code', 'debug_message')) GAME_PORT = 5056 FRAG_HEADER_LEN = 20 # 5 x u32 class DecodeError(Exception): pass def _need(buf: bytes, pos: int, n: int, what: str): if pos + n > len(buf): raise DecodeError(f"not enough bytes for {what} at {pos}") def rd_u8(buf: bytes, pos: int): _need(buf, pos, 1, "u8") return buf[pos], pos + 1 def rd_i16le(buf: bytes, pos: int): _need(buf, pos, 2, "i16le") return struct.unpack("H", buf[pos:pos + 2])[0], pos + 2 def rd_u32be(buf: bytes, pos: int): _need(buf, pos, 4, "u32be") return struct.unpack(">I", buf[pos:pos + 4])[0], pos + 4 def rd_u32le(buf: bytes, pos: int): _need(buf, pos, 4, "u32le") return struct.unpack("> 1) ^ (-(v & 1)) def read_string18(buf: bytes, pos: int): slen, pos = rd_varint(buf, pos) if slen == 0: return "", pos _need(buf, pos, slen, "string") return buf[pos:pos + slen].decode('utf-8', 'replace'), pos + slen def deserialize18(buf: bytes, pos: int, tc: int): if tc >= P18['CustomTypeSlim']: return ('custom', tc - P18['CustomTypeSlim']), pos if tc == P18['Boolean']: v, p = rd_u8(buf, pos) return bool(v), p if tc in (P18['Byte'], P18['ByteZero']): if tc == P18['ByteZero']: return 0, pos return rd_u8(buf, pos) if tc == P18['Short']: return rd_i16le(buf, pos) if tc == P18['Float']: return rd_f32le(buf, pos) if tc == P18['Double']: return rd_f64le(buf, pos) if tc == P18['String']: return read_string18(buf, pos) if tc == P18['Null']: return None, pos if tc == P18['BooleanFalse']: return False, pos if tc == P18['BooleanTrue']: return True, pos if tc in (P18['ShortZero'], P18['IntZero'], P18['LongZero']): return 0, pos if tc in (P18['FloatZero'], P18['DoubleZero']): return 0.0, pos if tc == P18['CompressedInt']: v, p = rd_varint(buf, pos) return zigzag(v), p if tc == P18['CompressedLong']: v, p = rd_varint(buf, pos) return zigzag(v), p if tc in (P18['Int1'], P18['Long1']): return rd_u8(buf, pos) if tc == P18['Int1Neg'] or tc == P18['Long1Neg']: v, p = rd_u8(buf, pos) return -v, p if tc in (P18['Int2'], P18['Long2']): return rd_u16le(buf, pos) if tc == P18['Int2Neg'] or tc == P18['Long2Neg']: v, p = rd_u16le(buf, pos) return -v, p if tc == P18['ByteArray']: n, p = rd_varint(buf, pos) _need(buf, p, n, "byte array") return bytes(buf[p:p + n]), p + n if tc == P18['ShortArray']: return _read_number_array(buf, pos, lambda b, p: rd_i16le(b, p), "short array") if tc == P18['FloatArray']: return _read_number_array(buf, pos, rd_f32le, "float array") if tc == P18['DoubleArray']: return _read_number_array(buf, pos, rd_f64le, "double array") if tc == P18['StringArray']: n, p = rd_varint(buf, pos) out = [] for _ in range(n): s, p = read_string18(buf, p) out.append(s) return out, p if tc == P18['CompressedIntArray']: n, p = rd_varint(buf, pos) out = [] for _ in range(n): v, p = rd_varint(buf, p) out.append(zigzag(v)) return out, p if tc == P18['CompressedLongArray']: n, p = rd_varint(buf, pos) out = [] for _ in range(n): v, p = rd_varint(buf, p) out.append(zigzag(v)) return out, p if tc == P18['BooleanArray']: n, p = rd_varint(buf, pos) out = [] for _ in range(n): v, p = rd_u8(buf, p) out.append(bool(v)) return out, p if tc in (P18['Array'], P18['ObjectArray'], P18['CustomTypeArray']): n, p = rd_varint(buf, pos) out = [] for _ in range(n): et, p = rd_u8(buf, p) v, p = deserialize18(buf, p, et) out.append(v) return out, p if tc in (P18['Dictionary'], P18['Hashtable'], P18['DictionaryArray'], P18['HashtableArray']): return _decode_map18(buf, pos, tc) if tc == P18['Custom']: t, p = rd_u8(buf, pos) n, p = rd_varint(buf, p) _need(buf, p, n, "custom") return ('custom', t, bytes(buf[p:p + n])), p + n raise DecodeError(f"unhandled P18 type 0x{tc:02X} at {pos}") def _read_number_array(buf: bytes, pos: int, reader, what: str): n, p = rd_varint(buf, pos) out = [] for _ in range(n): v, p = reader(buf, p) out.append(v) return out, p def _decode_map18(buf: bytes, pos: int, tc: int): if tc in (P18['Dictionary'], P18['DictionaryArray']): kt, pos0 = rd_u8(buf, pos) vt, p = rd_u8(buf, pos0) n, p = rd_varint(buf, p) out = {} for _ in range(n): if kt == 0: kt2, p = rd_u8(buf, p) k, p = deserialize18(buf, p, kt2) else: k, p = deserialize18(buf, p, kt) if vt == 0: vt2, p = rd_u8(buf, p) v, p = deserialize18(buf, p, vt2) else: v, p = deserialize18(buf, p, vt) out[k] = v return out, p n, p = rd_varint(buf, pos) out = {} for _ in range(n): kt, p = rd_u8(buf, p) k, p = deserialize18(buf, p, kt) vt, p = rd_u8(buf, p) v, p = deserialize18(buf, p, vt) out[k] = v return out, p def decode_params18(buf: bytes, pos: int): size, pos = rd_u8(buf, pos) out = {} for _ in range(size): key, pos = rd_u8(buf, pos) tc, pos = rd_u8(buf, pos) val, pos = deserialize18(buf, pos, tc) out[key] = val return out, pos def decode_message18(buf: bytes, pos: int): _, pos = rd_u8(buf, pos) # signal byte 0xF3 msg_type, pos = rd_u8(buf, pos) msg_type &= 0x7F if msg_type in (MSG_OPERATION_REQUEST, MSG_INTERNAL_REQUEST): code, pos = rd_u8(buf, pos) params, pos = decode_params18(buf, pos) return PhotonMessage('Request', code, params, None, None), pos if msg_type in (MSG_OPERATION_RESPONSE, MSG_INTERNAL_RESPONSE): code, pos = rd_u8(buf, pos) ret, pos = rd_i16le(buf, pos) dv_type, pos = rd_u8(buf, pos) dv, pos = deserialize18(buf, pos, dv_type) params, pos = decode_params18(buf, pos) return PhotonMessage('Response', code, params, ret, dv), pos if msg_type == MSG_EVENT_DATA: code, pos = rd_u8(buf, pos) params, pos = decode_params18(buf, pos) return PhotonMessage('Event', code, params, None, None), pos raise DecodeError(f"unknown message type 0x{msg_type:02X}") class FragmentAssembler: """Reassembles eNet SendFragment sequences into whole Photon messages.""" def __init__(self): self._fragments: Dict[tuple, dict] = {} def add(self, peer: int, start_seq: int, fragment_count: int, fragment_number: int, total_length: int, data: bytes): key = (peer, start_seq) group = self._fragments.setdefault( key, {'count': fragment_count, 'parts': {}, 'total': total_length}) if group['count'] != fragment_count: self._fragments.pop(key, None) return None group['parts'][fragment_number] = data if len(group['parts']) < group['count']: return None payload = b''.join(group['parts'][i] for i in range(group['count'])) self._fragments.pop(key, None) return payload class PhotonDecoder: def __init__(self): self.assembler = FragmentAssembler() def decode_packet(self, payload: bytes, peer: int = 0) -> List[PhotonMessage]: messages: List[PhotonMessage] = [] try: return self._decode_packet(payload, peer, messages) except DecodeError as e: logger.debug("dropping undecodable UDP payload: %s", e) return messages def _decode_packet(self, payload: bytes, peer: int, messages: List[PhotonMessage]) -> List[PhotonMessage]: pos = 0 _peer, pos = rd_u16be(payload, pos) crc, pos = rd_u8(payload, pos) count, pos = rd_u8(payload, pos) _ts, pos = rd_u32be(payload, pos) _ch, pos = rd_u32be(payload, pos) for _ in range(count): cmd_type, pos = rd_u8(payload, pos) _channel, pos = rd_u8(payload, pos) _flags, pos = rd_u8(payload, pos) _reserved, pos = rd_u8(payload, pos) length, pos = rd_u32be(payload, pos) _seq, pos = rd_u32be(payload, pos) data_len = length - 12 if cmd_type == CMD_SEND_FRAGMENT: start_seq, pos = rd_u32be(payload, pos) fragment_count, pos = rd_u32be(payload, pos) fragment_number, pos = rd_u32be(payload, pos) total_length, pos = rd_u32be(payload, pos) _offset, pos = rd_u32be(payload, pos) data = payload[pos:pos + data_len - FRAG_HEADER_LEN] pos += data_len - FRAG_HEADER_LEN reassembled = self.assembler.add( peer, start_seq, fragment_count, fragment_number, total_length, data) if reassembled is not None: messages.extend(self._decode_message(reassembled, peer)) continue if cmd_type in (CMD_ACKNOWLEDGE, CMD_PING): pos += data_len continue if cmd_type == CMD_LOGOUT: continue if cmd_type in (CMD_SEND_RELIABLE, CMD_SEND_UNRELIABLE, CMD_SEND_UNRELIABLE_FRAGMENT): if cmd_type in (CMD_SEND_UNRELIABLE, CMD_SEND_UNRELIABLE_FRAGMENT): pos += 4 # unknown/unreliable sequence trailers data_len -= 4 msg_bytes = payload[pos:pos + data_len] pos += data_len messages.extend(self._decode_message(msg_bytes, peer)) continue pos += data_len return messages def _decode_message(self, msg_bytes: bytes, peer: int) -> List[PhotonMessage]: if not msg_bytes: return [] signal = msg_bytes[0] if signal != PROTOCOL18_SIGNAL: logger.debug("dropping message with unknown signal 0x%02X", signal) return [] try: msg, _ = decode_message18(msg_bytes, 0) except DecodeError as e: logger.debug("dropping undecodable Photon message: %s", e) return [] logger.debug("decoded Photon message: %s", msg) return [msg]