Commit 8c4e52f6 authored by aleajactaest's avatar aleajactaest
Browse files

update decoder database.xml

parent 8e9c92c5
......@@ -107,9 +107,10 @@ class SpyPcap():
databaseRawXml = fp.read()
fp.close()
self.databaseXml = ET.fromstring(databaseRawXml)
self.decodeImpulseSimple.loadDatabase(self.databaseXml)
#self.decodeImpulseSimple.loadDatabase(self.databaseXml)
self.decodeDatabase = DecodeDatabase.DecodeDatabase()
self.decodeDatabase.loadDatabase(self.databaseXml)
self.decodeImpulseSimple.loadDatabase(self.decodeDatabase)
# outyaml
self.outyaml = outyaml
......@@ -946,12 +947,13 @@ def main():
# logger.append(logging.getLogger(CStringManager.LOGGER))
#logger.append(logging.getLogger(CAction.LOGGER))
#logger.append(logging.getLogger(CActionFactory.LOGGER))
# logger.append(logging.getLogger(BitStream.LOGGER))
logger.append(logging.getLogger(BitStream.LOGGER))
#logger.append(logging.getLogger(DecodeDatabase.LOGGER))
#logger.append(logging.getLogger(Impulse.LOGGER))
#logger.append(logging.getLogger(TVPNodeBase.LOGGER))
# CImpulseDecoder
# logger.append(logging.getLogger('CGenericMultiPartTemp'))
logger.append(logging.getLogger(DecodeDatabase.LOGGER))
parser = argparse.ArgumentParser()
parser.add_argument("--khanat-host-service", help="filter to detect khanat host:service (FES)")
......
......@@ -24,6 +24,7 @@ import sys
import inspect
import copy
import struct
from tools import CBitSet
LOGGER='BitStream'
......@@ -536,7 +537,7 @@ class BitStream():
self._groupWrite.append((p1, p2, name, 'BitStream', ''))
# ------------------------------------
def readSerial(self, nbits, name="", decode=True, typeName='', emulate=False, signed=False):
def readSerial(self, nbits, name="", decode=True, typeName='', emulate=False, signed=False, commentValue=None):
v1 = self._read
if nbits == 0:
return
......@@ -564,10 +565,10 @@ class BitStream():
if decode and not emulate:
if signed:
value = c_int32(value).value
self._groupRead.append((v1, v1+nbits, name, typeName, value))
self._groupRead.append((v1, v1+nbits, name, typeName, value, commentValue))
return value
def readSerial64(self, nbits, name="", decode=True, typeName=None):
def readSerial64(self, nbits, name="", decode=True, typeName=None, commentValue=None):
if nbits > 32:
v1 = self._read
msd = self.readSerial(nbits - 32, name, False, typeName)
......@@ -576,17 +577,83 @@ class BitStream():
if decode:
if typeName is None:
typeName = 'Uint{0}'.format(nbits)
self._groupRead.append((v1, v1+nbits, name, typeName, value))
self._groupRead.append((v1, v1+nbits, name, typeName, value, commentValue))
return value
else:
if typeName is None:
typeName = 'Uint{0}'.format(nbits)
return self.readSerial(nbits, name, decode, typeName)
return self.readSerial(nbits, name, decode, typeName, commentValue=commentValue)
def readCBitSet(self, nbits, name="", decode=True, typeName=None, commentValue=None):
# khanat-opennel-code/code/nel/src/misc/bit_mem_stream.cpp void CBitMemStream::readBits( NLMISC::CBitSet& bitfield )
cBitSet = CBitSet.CBitSet()
v1 = self._read
cBitSet.resize(nbits)
pos = 0
last = nbits
logging.getLogger(LOGGER).debug("nbits:%d" % nbits)
while last >= cBitSet.NL_BITLEN:
v = self.readSerial(cBitSet.NL_BITLEN, decode=False)
logging.getLogger(LOGGER).debug("pos:%d v:%d reel:%d" % (pos, v, (nbits//32)-pos-1))
cBitSet.setUint(v, (nbits//32)-pos-1)
last -= cBitSet.NL_BITLEN
pos += 1
if last > 0:
v = self.readSerial(last, decode=False)
logging.getLogger(LOGGER).debug("pos:%d v:%d reel:%d" % (pos, v, (nbits//32)-pos-1))
cBitSet.setUint(v, (nbits//32)-pos-1)
# pos = 0
# while pos < nbits:
# v = self.readSerial(1, decode=False)
# cBitSet.set(pos, v)
# pos += 1
if decode:
valuereal = cBitSet.showBitString()
_size = len(valuereal)
_start = _size - nbits
self._groupRead.append((v1, v1+nbits, name, typeName, valuereal[0:nbits], commentValue))
return cBitSet
def readCBitSetOld2(self, nbits, name="", decode=True, typeName=None, commentValue=None):
# khanat-opennel-code/code/nel/src/misc/bit_mem_stream.cpp void CBitMemStream::readBits( NLMISC::CBitSet& bitfield )
cBitSet = CBitSet.CBitSet()
v1 = self._read
cBitSet.resize(nbits)
pos = 0
logging.getLogger(LOGGER).debug("nbits:%d" % nbits)
pos = 0
while pos < nbits:
v = self.readSerial(1, decode=False)
logging.getLogger(LOGGER).debug("pos:%d value:%d" % (nbits-pos-1, v))
cBitSet.set(nbits-pos-1, v)
pos += 1
if decode:
self._groupRead.append((v1, v1+nbits, name, typeName, '', commentValue))
logging.getLogger(LOGGER).debug("cBitSet:%s" % cBitSet.showBitString())
return cBitSet
def readCBitSetOld3(self, nbits, name="", decode=True, typeName=None, commentValue=None):
# khanat-opennel-code/code/nel/src/misc/bit_mem_stream.cpp void CBitMemStream::readBits( NLMISC::CBitSet& bitfield )
cBitSet = CBitSet.CBitSet()
v1 = self._read
cBitSet.resize(nbits)
pos = 0
logging.getLogger(LOGGER).debug("nbits:%d" % nbits)
pos = 0
while pos < nbits:
v = self.readSerial(1, decode=False)
logging.getLogger(LOGGER).debug("pos:%d value:%d" % (nbits-pos-1, v))
cBitSet.set(pos, v)
pos += 1
if decode:
self._groupRead.append((v1, v1+nbits, name, typeName, '', commentValue))
logging.getLogger(LOGGER).debug("cBitSet:%s" % cBitSet.showBitString())
return cBitSet
def readBool(self, name):
v1 = self._read
v = self.readSerial(1, name=name, decode=False, typeName='Bool')
self._groupRead.append((v1, v1+1, name, 'Bool', 'True' if v != 0 else 'False'))
self._groupRead.append((v1, v1+1, name, 'Bool', 'True' if v != 0 else 'False', None))
if v != 0:
return True
else:
......@@ -638,7 +705,7 @@ class BitStream():
v7 = self.readSerial(8, decode=False)
v8 = self.readSerial(8, decode=False)
ret = v8 << 56 | v7 << 48 | v6 << 40 | v5 << 32 | v4 << 24 | v3 << 16 | v2 << 8 | v1
self._groupRead.append((p1, p1+64, name, 'Uint64', ret))
self._groupRead.append((p1, p1+64, name, 'Uint64', ret, None))
return v3
def readSint64(self, name):
......@@ -663,7 +730,7 @@ class BitStream():
v7 = self.readSerial(8, decode=False)
v8 = self.readSerial(8, decode=False)
ret = v8 << 56 | v7 << 48 | v6 << 40 | v5 << 32 | v4 << 24 | v3 << 16 | v2 << 8 | v1
self._groupRead.append((p1, p1+64, name, 'Sint64', c_int64(ret).value))
self._groupRead.append((p1, p1+64, name, 'Sint64', c_int64(ret).value, None))
return c_int64(v3).value
def readFloat(self, name):
......@@ -671,7 +738,7 @@ class BitStream():
v = self.readSerial(32, name=name, decode=False, typeName='Float')
v1 = struct.pack('I', v)
v2 = struct.unpack('<f',v1)[0]
self._groupRead.append((p1, p1+32, name, 'Float', v2))
self._groupRead.append((p1, p1+32, name, 'Float', v2, None))
return v2
def readDouble(self, name):
......@@ -682,7 +749,7 @@ class BitStream():
w1 = struct.pack('I', w)
x = v1 + w1
x1 = struct.unpack('<d', x)[0]
self._groupRead.append((p1, p1+64, name, 'Double', x1))
self._groupRead.append((p1, p1+64, name, 'Double', x1, None))
return x1
def readChar(self, name, decode=True):
......@@ -701,7 +768,7 @@ class BitStream():
if v2 > self._pos:
raise ValueError
if v1 < v2:
self._groupRead.append((v1, v2, name + ':string', 'String', tmp))
self._groupRead.append((v1, v2, name + ':string', 'String', tmp, None))
return tmp
def readUtf8String(self, name):
......@@ -716,7 +783,7 @@ class BitStream():
if v2 > self._pos:
raise ValueError
if v1 < v2:
self._groupRead.append((v1, v2, name + ':ustring', 'UString', tmp))
self._groupRead.append((v1, v2, name + ':ustring', 'UString', tmp, None))
return tmp.decode(encoding='utf-8')
def readUString(self, name):
......@@ -731,7 +798,7 @@ class BitStream():
if v2 > self._pos:
raise ValueError
if v1 < v2:
self._groupRead.append((v1, v2, name + ':ustring', 'UString', tmp))
self._groupRead.append((v1, v2, name + ':ustring', 'UString', tmp, None))
return tmp
def readArrayUint8(self, size, name):
......@@ -740,7 +807,7 @@ class BitStream():
for i in range(0, size):
ret.append(self.readUint8('', decode=False))
v2 = self._read
self._groupRead.append((v1, v2, name, 'ArrayUint8', ''))
self._groupRead.append((v1, v2, name, 'ArrayUint8', '', None))
return ret
def readBitStreamUint8(self, size, name):
......@@ -749,7 +816,7 @@ class BitStream():
for i in range(0, size):
ret.pushUint8(self.readUint8('', decode=False), decode=False)
v2 = self._read
self._groupRead.append((v1, v2, name, 'StreamUint8', ''))
self._groupRead.append((v1, v2, name, 'StreamUint8', '', None))
return ret
def readCont(self, name):
......@@ -759,7 +826,7 @@ class BitStream():
for i in range(0, size):
ret.pushBool(self.readSerial(1,name = '', decode=False))
v2 = self._read
self._groupRead.append((v1, v2, name + ':data', 'readCont', ''))
self._groupRead.append((v1, v2, name + ':data', 'readCont', '', None))
return size, ret
def getNotRead(self):
......@@ -851,8 +918,18 @@ class BitStream():
ret2 = ""
last = 0
for x, y, name, typeName, value in self._groupRead:
ret2 += "[<" + str(x) + ':' + str(y-1) + "> " + str(name) + ' (' + typeName + ') : ' + ret[x:y] + ' => ' + str(value) + "]"
for x, y, name, typeName, value, commentValue in self._groupRead:
if typeName == None:
typeName = '-'
if commentValue == None:
strcommentValue = ""
else:
strcommentValue = " " + commentValue
if value:
strvalue = ' => ' + str(value)
else:
strvalue = ''
ret2 += "[<" + str(x) + ':' + str(y-1) + "> " + str(name) + ' (' + typeName + ') : ' + ret[x:y] + strvalue + strcommentValue + "]"
last = y
if last < self._pos:
ret2 += "{" + ret[last:] + "}"
......@@ -890,6 +967,8 @@ class BitStream():
last = 0
for x, y, name, typeName, value in self._groupWrite:
if typeName == None:
typeName = '-'
ret2 += "[<" + str(x) + ':' + str(y-1) + "> " + str(name) + ' (' + typeName + ') : ' + ret[x:y] + ' => ' + str(value) + "]"
last = y
if last < self._pos:
......@@ -958,13 +1037,18 @@ class BitStream():
ret2 = []
last = 0
for x, y, name, typeName, value in self._groupRead:
for x, y, name, typeName, value, commentValue in self._groupRead:
if commentValue == None:
commentValue = ""
plus = ""
else:
plus = " "
if not typeName:
nbbit = y - x
typeName = "%d bit" % nbbit
if nbbit > 1:
typeName += "s"
ret2.append("<" + str(x) + ':' + str(y-1) + "> " + '(' + typeName + ') ' + str(name) + ' => ' + str(value) + " : " + ret[x:y])
ret2.append("<" + str(x) + ':' + str(y-1) + "> " + '(' + typeName + ') ' + str(name) + ' => ' + str(value) + " : " + ret[x:y] + plus + commentValue)
last = y
if last < self._pos:
ret2.append("<" + str(last) + ':' + str(self._pos - 1) + "> " + ret[last:])
......
......@@ -57,6 +57,9 @@ class CBitSet:
mask= bitNumber&(self.NL_BITLEN-1);
mask= 1<<mask;
return self.data[bitNumber >> 5] & mask != 0
def setUint(self, srcValue, i):
self.data[i] = srcValue
def setBit(self, bitNumber):
self.set(bitNumber, True)
......@@ -66,6 +69,10 @@ class CBitSet:
def __str__(self):
return '.'.join([hex(x) for x in self.data])
def showBitString(self):
return ''.join(["{0:032b}".format(x) for x in reversed(self.data)])
def writeSerial(self, msgout):
# v = 0 # currentVersion
# if v >= 0xff:
......@@ -94,6 +101,23 @@ class CBitSet:
y = msgin.readUint32( name+':Data' )
self.data[i] = y
def readSerialExtra(self, msgin, nbBit, name):
needread = nbBit
print("----", nbBit, nbBit // 32 + 1)
self.resize(nbBit)
i = 0
while needread>32:
print("---<", nbBit, nbBit // 32 + 1, i, needread)
y = msgin.readUint32( name+' Data' + str(i))
self.data[i] = y
needread -= 32
i += 1
print(self.data)
if needread > 0:
print("--->", nbBit, nbBit // 32 + 1, i, needread)
y = msgin.readSerial( needread, name+' Data' + str(i), typeName="I" + str(needread) )
self.data[i] = y
def TestCBitSet():
cBitSet = CBitSet()
cBitSet.resize(1024)
......
......@@ -20,17 +20,21 @@
import logging
from tools import getPowerOf2
from tools import BitStream
LOGGER='DecodeDatabase'
def show_dico(dico, level=1):
for ele in dico:
if isinstance(dico[ele], dict):
print("." * level, ele , ":")
try:
for ele in dico:
if isinstance(dico[ele], dict):
show_dico(dico[ele], level+1)
else:
print("." * level, ele, ':', dico[ele])
print("." * level, ele , ":")
if isinstance(dico[ele], dict):
show_dico(dico[ele], level+1)
else:
print("." * level, ele, ':', dico[ele])
except:
print("empty")
def child(ele):
ret = {}
......@@ -77,63 +81,452 @@ def child(ele):
return ret
def count_elements(head):
print("%" * 80)
#print(head)
if 'child' in head.keys():
list_ele = [x for x in list(head['child'].keys()) if isinstance(x, int)]
else:
list_ele = [x for x in list(head.keys()) if isinstance(x, int)]
print(list_ele)
last_key = max(list_ele)
print(last_key )
print("%" * 80)
try:
return head.items()[-1]['max'] + 1
last_key = max(list_ele)
if 'child' in head.keys():
return head['child'][last_key]['max'] + 1
else:
return head[last_key]['max'] + 1
except TypeError:
return len(head)
return 0
def get_element(head, id):
print("id:", id)
for ele in head:
if id <= head[ele]['max'] and id >= head[ele]['min']:
return head[ele]
for ele in head['child']:
print("ele:", ele)
print("head:", head)
print("max:", head['child'][ele]['max'])
print("min:", head['child'][ele]['min'])
if id <= head['child'][ele]['max'] and id >= head['child'][ele]['min']:
return head['child'][ele]
return None
class LeafDatabase():
def __init__(self):
self.name = ""
self.type = ""
self.count = None
def loadXml(self, xmldata):
self.name = xmldata.get('name')
self.type = xmldata.get('type')
if xmldata.get('count'):
self.count = int(xmldata.get('count'))
def countLeaves(self):
if self.count:
return self.count
else:
return 1
def show(self, level=1):
print(" " * level, level, " Leaf ", self.name, ":", self.count, ":", self.type)
def execute(self, msgin, name=""):
if name:
tmp = "/" + name
else:
tmp = "/" + self.name
if self.type[0] == 'I':
logging.getLogger(LOGGER).debug("Read:" + str (self.type))
value = int(self.type[1:])
_ = msgin.readSerial64(value, name='DatabaseXML' + tmp, typeName=self.type)
else:
logging.getLogger(LOGGER).debug("Type inconnu:" + str (self.type))
raise "type not managed"
def execute_atom(self, level, pos, msgin, name=""):
if name:
extraName = "/" + name + "/" + self.name
else:
extraName = "/" + self.name
if self.count:
step = self.count
else:
step = 1
for step in range(0, step):
if self.count:
idname = extraName + str(step)
else:
idname = extraName
logging.getLogger(LOGGER).debug('step:' + str(step) + ' level:'+ str(level) + ' pos:' + str(pos) + ' idname:' + idname)
if level < pos:
level += 1
continue
if self.type[0] == 'I':
value = int(self.type[1:])
_ = msgin.readSerial(value, name='DatabaseXML' + idname, typeName=self.type)
return level+1
else:
logging.getLogger(LOGGER).debug("Type inconnu:", self.type)
raise "type not managed"
return level
class BranchDatabase():
def __init__(self):
self.name = None
self.branch = []
self.leaf = []
self.min = None
self.max = None
self.atom = False
self.count = None
def loadXml(self, xmldata, filter=None):
# print("xmldata:", xmldata)
# print("keys:", xmldata.keys())
# print("filter:", filter)
#print("bank:", xmldata['bank'])
if filter:
if 'bank' in xmldata:
if filter != xmldata['bank']:
return
else:
return
if xmldata.get('atom'):
self.atom = True
if xmldata.get('count'):
self.count = int(xmldata.get('count'))
self.name = xmldata.get('name')
# print(self.name)
for ele in xmldata:
if ele.tag == 'branch':
newbranch = BranchDatabase()
newbranch.loadXml(ele)
self.branch.append(newbranch)
elif ele.tag == 'leaf':
newleaf = LeafDatabase()
newleaf.loadXml(ele)
self.leaf.append(newleaf)
def loadRootXml(self, xmldata, filter=None):
for ele in xmldata:
if ele.tag == 'branch':
if filter:
if ele.get('bank') == filter:
# print(ele.get('bank'), filter)
newbranch = BranchDatabase()
newbranch.loadXml(ele)
self.branch.append(newbranch)
def getIdBits(self):
count = 0
for ele in self.branch:
if ele.count:
count += ele.count
else:
count += 1
for ele in self.leaf:
if ele.count:
count += ele.count
else:
count += 1
return count
def countLeaves(self):
count = 0
for ele in self.branch:
count += ele.countLeaves()
for ele in self.leaf:
count += ele.countLeaves()
if self.count:
count *= self.count
return count
def execute_atom_found(self, level, pos, msgin, name=""):
if self.count:
step = self.count
else:
step=1
if name:
extraName = name + "/" + self.name
else:
extraName = self.name
for step in range(0, step):
logging.getLogger(LOGGER).debug('step:' + str(step)+ ' level:' + str(level) + ' pos:' + str(pos) + ' name:' + name)
if self.count:
idname = extraName + str(step)
else:
idname = extraName
for ele in self.branch:
level = ele.execute_atom_found(level, pos, msgin, idname)
logging.getLogger(LOGGER).debug('step:' + str(step)+ ' level:' + str(level) + ' pos:' + str(pos) + ' name:' + name + ' idname:' + str(idname))
if level > pos:
return level
for ele in self.leaf:
level = ele.execute_atom(level, pos, msgin, idname)
logging.getLogger(LOGGER).debug('step:' + str(step)+ ' level:' + str(level) + ' pos:' + str(pos) + ' name:' + name + ' idname:' + str(idname))
if level > pos:
return level
return level
def show(self, level=0, pos=0, filterlevel=None):
print(" " * level, level, "pos:", pos, " Branch ", self.name, ":", self.count, ":", self.atom, self.getIdBits())
if filterlevel is not None:
if filterlevel <= level:
return
i = 0
for ele in self.branch:
ele.show(level + 1, i, filterlevel)
i += 1
for ele in self.leaf:
ele.show(level + 1)
def execute_atom(self, msgin):
nbchild = self.countLeaves()
#nbBit = getPowerOf2.getPowerOf2_Bis(nbchild)
logging.getLogger(LOGGER).debug("needRead:" + str(msgin.needRead()) + " nbchild:" + str(nbchild))
logging.getLogger(LOGGER).debug(msgin.showAllData())
cBitSet = msgin.readCBitSet(nbchild, self.name + ":Param", typeName = 'I' + str(nbchild))
#cBitSet = CBitSet.CBitSet()
#cBitSet.readSerialExtra(msgin, nbchild, self.name + "/Param")
logging.getLogger(LOGGER).debug(msgin.showAllData())
todelete_count_true = 0
for i in range(0, nbchild):
#ii = nbchild - i
logging.getLogger(LOGGER).debug(str(i) + " - " + str(cBitSet.get(i)))
if cBitSet.get(i):
todelete_count_true += 1
_ = self.execute_atom_found(0, i, msgin)
if todelete_count_true > 1:
logging.getLogger(LOGGER).debug(msgin.showAllData())
#raise "A controler"
logging.getLogger(LOGGER).debug(msgin.showAllDataRaw())
logging.getLogger(LOGGER).debug(msgin.showAllData())
#raise "A faire"
def execute_normal(self, msgin):
nbchild = self.getIdBits()
#nbBit = getPowerOf2.getPowerOf2_Bis(nbchild)
nbBit = getPowerOf2.getPowerOf2_ter(nbchild)
if nbBit > msgin.needRead() :
return
logging.getLogger(LOGGER).debug("needRead:" + str(msgin.needRead()) + " nbBit:" + str(nbBit))
id = msgin.readSerial(nbBit, name='DatabaseXML', typeName='Number:'+str(nbBit), emulate=True)
i = 0