-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathliqi.py
252 lines (219 loc) · 8.73 KB
/
liqi.py
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import os
import json
import struct
import base64
from enum import Enum
from typing import List, Tuple, Dict
from google.protobuf.json_format import MessageToDict, ParseDict
from liqi_proto import liqi_pb2 as pb
from rich.console import Console
console = Console()
class MsgType(Enum):
Notify = 1
Req = 2
Res = 3
keys = [0x84, 0x5e, 0x4e, 0x42, 0x39, 0xa2, 0x1f, 0x60, 0x1c]
def decode(data: bytes):
data = bytearray(data)
for i in range(len(data)):
u = (23 ^ len(data)) + 5 * i + keys[i % len(keys)] & 255
data[i] ^= u
return bytes(data)
# Just XOR it back
def encode(data: bytes):
data = bytearray(data)
for i in range(len(data)):
u = (23 ^ len(data)) + 5 * i + keys[i % len(keys)] & 255
data[i] ^= u
return bytes(data)
class LiqiProto:
def __init__(self):
self.msg_id = 1
self.tot = 0
self.res_type = dict()
self.jsonProto = json.load(
open(os.path.join(os.path.dirname(__file__), 'liqi_proto/liqi.json'), 'r'))
def init(self):
self.msg_id = 1
self.res_type.clear()
def parse(self, flow_msg, injected=False) -> dict:
if isinstance(flow_msg, bytes):
buf = flow_msg
else:
buf = flow_msg.content
from_client = flow_msg.from_client
result = dict()
try:
msg_type = MsgType(buf[0])
if msg_type == MsgType.Notify:
msg_block = fromProtobuf(buf[1:])
method_name = msg_block[0]['data'].decode()
_, lq, message_name = method_name.split('.')
liqi_pb2_notify = getattr(pb, message_name)
proto_obj = liqi_pb2_notify.FromString(msg_block[1]['data'])
dict_obj = MessageToDict(proto_obj, including_default_value_fields=True)
if 'data' in dict_obj:
B = base64.b64decode(dict_obj['data'])
action_proto_obj = getattr(pb, dict_obj['name']).FromString(decode(B))
action_dict_obj = MessageToDict(action_proto_obj, including_default_value_fields=True)
dict_obj['data'] = action_dict_obj
msg_id = -1
else:
msg_id = struct.unpack('<H', buf[1:3])[0]
msg_block = fromProtobuf(buf[3:])
if msg_type == MsgType.Req:
assert(msg_id < 1 << 16)
assert(len(msg_block) == 2)
assert(msg_id not in self.res_type)
method_name = msg_block[0]['data'].decode()
_, lq, service, rpc = method_name.split('.')
proto_domain = self.jsonProto['nested'][lq]['nested'][service]['methods'][rpc]
liqi_pb2_req = getattr(pb, proto_domain['requestType'])
proto_obj = liqi_pb2_req.FromString(msg_block[1]['data'])
dict_obj = MessageToDict(proto_obj, including_default_value_fields=True)
self.res_type[msg_id] = (method_name, getattr(
pb, proto_domain['responseType']))
self.msg_id = msg_id
elif msg_type == MsgType.Res:
assert(len(msg_block[0]['data']) == 0)
assert(msg_id in self.res_type)
method_name, liqi_pb2_res = self.res_type.pop(msg_id)
proto_obj = liqi_pb2_res.FromString(msg_block[1]['data'])
dict_obj = MessageToDict(proto_obj, including_default_value_fields=True)
else:
console.log('unknow msg:', buf, style='bold red')
return None
result = {'id': msg_id, 'type': msg_type,
'method': method_name, 'data': dict_obj}
self.tot += 1
except Exception as e:
console.log(f'error: {e} unknow msg:', buf, style='bold red')
return None
return result
def parse_syncGame(self, syncGame):
assert syncGame['method'] == '.lq.FastTest.syncGame' or syncGame['method'] == '.lq.FastTest.enterGame'
msgs = []
if 'gameRestore' in syncGame['data']:
for action in syncGame['data']['gameRestore']['actions']:
msgs.append(self.parse_syncGameActions(action))
return msgs
def parse_syncGameActions(self, dict_obj):
dict_obj['data'] = MessageToDict(getattr(pb, dict_obj['name']).FromString(base64.b64decode(dict_obj['data'])), including_default_value_fields=True)
msg_id = -1
result = {'id': msg_id, 'type': MsgType.Notify,
'method': '.lq.ActionPrototype', 'data': dict_obj}
return result
def compose(self, data, msg_id=-1):
if data['type'] == MsgType.Notify:
return self.compose_notify(data)
msg_block = [
{'id': 1, 'type': 'string', 'data': b'.lq.FastTest.authGame'},
{'id': 2, 'type': 'string','data': b'protobuf_bytes'}
]
_, lq, service, rpc = data['method'].split('.')
proto_domain = self.jsonProto['nested'][lq]['nested'][service]['methods'][rpc]
if data['type'] == MsgType.Req:
message = ParseDict(data['data'], getattr(pb, proto_domain['requestType'])())
elif data['type'] == MsgType.Res:
message = ParseDict(data['data'], getattr(pb, proto_domain['responseType'])())
msg_block[0]['data'] = data['method'].encode()
msg_block[1]['data'] = message.SerializeToString()
if msg_id == -1:
compose_id = (self.msg_id-8)%256
else:
compose_id = msg_id
if data['type'] == MsgType.Req:
composed = b'\x02' + struct.pack('<H', compose_id) + toProtobuf(msg_block)
self.parse(composed)
return composed
elif data['type'] == MsgType.Res:
composed = b'\x03' + struct.pack('<H', compose_id) + toProtobuf(msg_block)
return composed
else:
raise
def compose_notify(self, data):
msg_block = [
{'id': 1, 'type': 'string', 'data': b'.lq.FastTest.authGame'},
{'id': 2, 'type': 'string','data': b'protobuf_bytes'}
]
_, lq, message_name = data['method'].split('.')
msg_block[0]['data'] = data['method'].encode()
msg_block[1]['data'] = ...
if 'data' in data['data']:
action_dict_obj = data['data']['data']
action_proto_obj = ParseDict(action_dict_obj, getattr(pb, data['data']['name'])())
action_proto_obj = action_proto_obj.SerializeToString()
B = encode(action_proto_obj)
data['data']['data'] = base64.b64encode(B)
message = ParseDict(data['data'], getattr(pb, message_name)())
msg_block[1]['data'] = message.SerializeToString()
composed = b'\x01' + toProtobuf(msg_block)
return composed
def toVarint(x: int) -> bytes:
data = 0
base = 0
length = 0
if x == 0:
return b'\x00'
while(x > 0):
length += 1
data += (x & 127) << base
x >>= 7
if x > 0:
data += 1 << (base+7)
base += 8
return data.to_bytes(length, 'little')
def parseVarint(buf, p):
# parse a varint from protobuf
data = 0
base = 0
while(p < len(buf)):
data += (buf[p] & 127) << base
base += 7
p += 1
if buf[p-1] >> 7 == 0:
break
return (data, p)
def fromProtobuf(buf) -> List[Dict]:
# """
# dump the struct of protobuf,观察报文结构
# buf: protobuf bytes
# """
p = 0
result = []
while(p < len(buf)):
block_begin = p
block_type = (buf[p] & 7)
block_id = buf[p] >> 3
p += 1
if block_type == 0:
#varint
block_type = 'varint'
data, p = parseVarint(buf, p)
elif block_type == 2:
#string
block_type = 'string'
s_len, p = parseVarint(buf, p)
data = buf[p:p+s_len]
p += s_len
else:
raise Exception('unknow type:', block_type, ' at', p)
result.append({'id': block_id, 'type': block_type,
'data': data, 'begin': block_begin})
return result
def toProtobuf(data: List[Dict]) -> bytes:
# """
# Inverse operation of 'fromProtobuf'
# """
result = b''
for d in data:
if d['type'] == 'varint':
result += ((d['id'] << 3)+0).to_bytes(length=1, byteorder='little')
result += toVarint(d['data'])
elif d['type'] == 'string':
result += ((d['id'] << 3)+2).to_bytes(length=1, byteorder='little')
result += toVarint(len(d['data']))
result += d['data']
else:
raise NotImplementedError
return result