Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathdecoder.py
More file actions
Latest commit
192 lines (175 loc) · 7.21 KB
/
Copy pathdecoder.py
File metadata and controls
192 lines (175 loc) · 7.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
fromcollectionsimportOrderedDict
fromcoc.message.readerimportCoCMessageReader
fromcoc.message.definitionsimportCoCMessageDefinitions
importjson
importmath
fromcoc.hexdumpimporthexdump
classCoCMessageDecoder:
lengthTypes= ['BYTE', 'INT', 'RRSINT32']
_bitfield=None
def__init__(self, definitions=None):
ifnotdefinitions:
self._definitions=CoCMessageDefinitions.read()
self._definitions=definitions
defdecodeFile(self, filepath):
messageid=None
length=None
version=None
payload=None
withopen(filepath, 'rb') asfh:
messageid=int.from_bytes(fh.read(2), byteorder="big")
length=int.from_bytes(fh.read(3), byteorder="big")
version=int.from_bytes(fh.read(2), byteorder="big")
payload=fh.read(length)
ifmessageidandlengthandpayload:
returnself.decode(messageid, version, payload)
returnNone
defdecode(self, messageid, unknown, payload):
ifmessageidinself._definitions:
reader=CoCMessageReader(messageid, unknown, payload)
if"fields"inself._definitions[messageid]:
decoded= {
"name": self._definitions[messageid]["name"],
"fields": self._decode_fields(reader, self._definitions[messageid]["fields"])
}
else:
decoded= {
"name": self._definitions[messageid]["name"]
}
unused=reader.read()
ifunused:
self.dump(decoded)
raiseIndexError("Unused {} bytes in buffer remains".
format(len(unused)))
returndecoded
else:
raiseKeyError("Message definition missing ({}).".format(messageid))
def_decode_fields(self, reader, fields):
decoded=OrderedDict()
forindex, fieldinenumerate(fields):
if"name"notinfield:
field["name"] ="unknown_{}".format(str(index).zfill(math.floor(math.log10(len(fields)))))
# default in lengthType to 4 byte int. Used to count the number of members in an array
if"lengthType"notinfield:
field["lengthType"] ="INT"
self._lengthTypeCheck(field["lengthType"])
value=self._decode_field(reader, field["name"], field["type"], field["lengthType"])
decoded[field["name"]] =value
returndecoded
def_lengthTypeCheck(self, lengthType):
iflengthTypenotinself.lengthTypes:
raiseValueError("lengthType {} not supported".format(lengthType))
def_decode_field(self, reader, name, type, lengthType):
ifnotlen(reader.peek(1)):
raiseIndexError("Read buffer out of data.")
iftype[:1] =="?":
ifself._bitfield:
self._bitfield= (self._bitfield<<1) %16
ifnotself._bitfield:
returnNone
else:
self._bitfield=1
ifreader.peek_int(1) &self._bitfield:
type=type[1:]
reader.read(1)
self._bitfield=None
else:
returnNone
elifself._bitfield:
reader.read(1)
self._bitfield=None
found=type.find("[")
iffound>=0:
count=type[found+1:-1]
type=type[:found]
ifnotcount:
iflengthType=="BYTE":
count=reader.read_int(1)
eliflengthType=="INT":
count=reader.read_int(4)
else:
count=reader.read_rrsint32()
decoded= []
foriinrange(int(count)):
decoded.append(self._decode_field(reader, "{}[{}]".format(name, i), type, lengthType))
returndecoded
eliftype=="BOOLEAN":
returnbool(reader.read_int(1))
eliftype=="BYTE":
returnreader.read_byte()
eliftype=="SCID":
returnreader.read_scid()
eliftype=="SHORT":
returnreader.read_short()
eliftype=="INT":
returnreader.read_int()
eliftype=="INT32":
returnreader.read_int32()
eliftype=="SINT32":
returnreader.read_sint32()
eliftype=="RRSINT32":
returnreader.read_rrsint32()
eliftype=="RRSLONG":
returnreader.read_rrslong()
eliftype=="LONG":
returnreader.read_long()
eliftype=="STRING":
returnreader.read_string()
eliftype=="ZIP_STRING":
decoded=reader.read_zstring()
ifnotdecoded:
returndecoded
try:
decoded=decoded.decode()
exceptUnicodeDecodeError:
raiseValueError("Failed to decode JSON.")
else:
returnjson.loads(decoded)
eliftype=="IGNORE":
# consume all the trailing data and ignore
ignore_count=0
whilelen(reader.peek(1)) >0:
ignore_count+=1
reader.read_byte()
return"{} bytes ignored".format(ignore_count)
eliftypeinself._definitions["component"]:
decoded=self._decode_fields(reader, self._definitions["component"][type]["fields"])
if"extensions"inself._definitions["component"][type]:
ifnotdecoded["id"] inself._definitions["component"][type]["extensions"]:
raiseNotImplementedError("{}(id={}) has not yet been implemented.".format(type, decoded["id"]))
decoded["payload"] =self._decode_fields(reader, self._definitions["component"][type]["extensions"][decoded["id"]]["fields"])
self.dump(decoded)
returndecoded
else:
raiseNotImplementedError("{} has not yet been implemented.".format(type))
defdump(self, decoded, hide_unknown=False):
if"name"notindecoded:
decoded["name"] ="unknownName"
if"fields"indecoded:
print("{}: {}".format(decoded["name"], json.dumps(self.stringify(decoded["fields"], hide_unknown), indent=2)))
else:
print("{}: {{}}".format(decoded["name"]))
defstringify(self, decoded, hide_unknown=False):
stringified=type(decoded)()
iftype(decoded) islist:
keys=range(len(decoded))
else:
keys=decoded.keys()
forkeyinkeys:
ifhide_unknownandkey[:len("unknown_")] =="unknown_":
continue
value=decoded[key]
iftype(value) isbytes:
try:
str=value.decode()
exceptUnicodeDecodeError:
str=value.hex()
eliftype(value) in {dict, list, OrderedDict}:
str=self.stringify(value)
else:
str=value
iftype(stringified) islist:
stringified.append(str)
else:
stringified[key] =str
returnstringified