我正在寻找解析asn.1规范文件并从中生成解码器的解决方案。
理想情况下,我想使用Python模块,但如果没有可用的话,我会使用C / C ++库并将它们与Python接口,并提供大量的解决方案。
在过去,我一直在使用pyasn1并手工制作所有东西,但这已经变得过于笨拙。
我也非常看好libtasn1和asn1c。第一个解析甚至最简单的文件都有问题。第二个有一个很好的解析器但是生成用于解码的C代码似乎太复杂了;该解决方案适用于简单的规范,但在复杂的规则上窒息。
我可能忽略了其他任何好的选择?
答案 0 :(得分:11)
几年前我写过这样的解析器。它为pyasn1库生成python类。我在ericsson doc上使用了为他们的CDR制作解析器。
我现在尝试在这里发布代码。
import sys
from pyparsing import *
OpenBracket = Regex("[({]").suppress()
CloseBracket = Regex("[)}]").suppress()
def Enclose(val):
return OpenBracket + val + CloseBracket
def SetDefType(typekw):
def f(a, b, c):
c["defType"] = typekw
return f
def NoDashes(a, b, c):
return c[0].replace("-", "_")
def DefineTypeDef(typekw, typename, typedef):
return typename.addParseAction(SetDefType(typekw)).setResultsName("definitionType") - \
Optional(Enclose(typedef).setResultsName("definition"))
SizeConstraintBodyOpt = Word(nums).setResultsName("minSize") - \
Optional(Suppress(Literal("..")) - Word(nums + "n").setResultsName("maxSize"))
SizeConstraint = Group(Keyword("SIZE").suppress() - Enclose(SizeConstraintBodyOpt)).setResultsName("sizeConstraint")
Constraints = Group(delimitedList(SizeConstraint)).setResultsName("constraints")
DefinitionBody = Forward()
TagPrefix = Enclose(Word(nums).setResultsName("tagID")) - Keyword("IMPLICIT").setResultsName("tagFormat")
OptionalSuffix = Optional(Keyword("OPTIONAL").setResultsName("isOptional"))
JunkPrefix = Optional("--F--").suppress()
AName = Word(alphanums + "-").setParseAction(NoDashes).setResultsName("name")
SingleElement = Group(JunkPrefix - AName - Optional(TagPrefix) - DefinitionBody.setResultsName("typedef") - OptionalSuffix)
NamedTypes = Dict(delimitedList(SingleElement)).setResultsName("namedTypes")
SetBody = DefineTypeDef("Set", Keyword("SET"), NamedTypes)
SequenceBody = DefineTypeDef("Sequence", Keyword("SEQUENCE"), NamedTypes)
ChoiceBody = DefineTypeDef("Choice", Keyword("CHOICE"), NamedTypes)
SetOfBody = (Keyword("SET") + Optional(SizeConstraint) + Keyword("OF")).setParseAction(SetDefType("SetOf")) + Group(DefinitionBody).setResultsName("typedef")
SequenceOfBody = (Keyword("SEQUENCE") + Optional(SizeConstraint) + Keyword("OF")).setParseAction(SetDefType("SequenceOf")) + Group(DefinitionBody).setResultsName("typedef")
CustomBody = DefineTypeDef("constructed", Word(alphanums + "-").setParseAction(NoDashes), Constraints)
NullBody = DefineTypeDef("Null", Keyword("NULL"), Constraints)
OctetStringBody = DefineTypeDef("OctetString", Regex("OCTET STRING"), Constraints)
IA5StringBody = DefineTypeDef("IA5String", Keyword("IA5STRING"), Constraints)
EnumElement = Group(Word(printables).setResultsName("name") - Enclose(Word(nums).setResultsName("value")))
NamedValues = Dict(delimitedList(EnumElement)).setResultsName("namedValues")
EnumBody = DefineTypeDef("Enum", Keyword("ENUMERATED"), NamedValues)
BitStringBody = DefineTypeDef("BitString", Keyword("BIT") + Keyword("STRING"), NamedValues)
DefinitionBody << (OctetStringBody | SetOfBody | SetBody | ChoiceBody | SequenceOfBody | SequenceBody | EnumBody | BitStringBody | IA5StringBody | NullBody | CustomBody)
Definition = AName - Literal("::=").suppress() - Optional(TagPrefix) - DefinitionBody
Definitions = Dict(ZeroOrMore(Group(Definition)))
pf = Definitions.parseFile(sys.argv[1])
TypeDeps = {}
TypeDefs = {}
def SizeConstraintHelper(size):
s2 = s1 = size.get("minSize")
s2 = size.get("maxSize", s2)
try:
return("constraint.ValueSizeConstraint(%s, %s)" % (int(s1), int(s2)))
except ValueError:
pass
ConstraintMap = {
'sizeConstraint' : SizeConstraintHelper,
}
def ConstraintHelper(c):
result = []
for key, value in c.items():
r = ConstraintMap[key](value)
if r:
result.append(r)
return result
def GenerateConstraints(c, ancestor, element, level=1):
result = ConstraintHelper(c)
if result:
return [ "subtypeSpec = %s" % " + ".join(["%s.subtypeSpec" % ancestor] + result) ]
return []
def GenerateNamedValues(definitions, ancestor, element, level=1):
result = [ "namedValues = namedval.NamedValues(" ]
for kw in definitions:
result.append(" ('%s', %s)," % (kw["name"], kw["value"]))
result.append(")")
return result
OptMap = {
False: "",
True: "Optional",
}
def GenerateNamedTypesList(definitions, element, level=1):
result = []
for val in definitions:
name = val["name"]
typename = None
isOptional = bool(val.get("isOptional"))
subtype = []
constraints = val.get("constraints")
if constraints:
cg = ConstraintHelper(constraints)
subtype.append("subtypeSpec=%s" % " + ".join(cg))
tagId = val.get("tagID")
if tagId:
subtype.append("implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, %s)" % tagId)
if subtype:
subtype = ".subtype(%s)" % ", ".join(subtype)
else:
subtype = ""
cbody = []
if val["defType"] == "constructed":
typename = val["typedef"]
element["_d"].append(typename)
elif val["defType"] == "Null":
typename = "univ.Null"
elif val["defType"] == "SequenceOf":
typename = "univ.SequenceOf"
print val.items()
cbody = [ " componentType=%s()" % val["typedef"]["definitionType"] ]
elif val["defType"] == "Choice":
typename = "univ.Choice"
indef = val.get("definition")
if indef:
cbody = [ " %s" % x for x in GenerateClassDefinition(indef, name, typename, element) ]
construct = [ "namedtype.%sNamedType('%s', %s(" % (OptMap[isOptional], name, typename), ")%s)," % subtype ]
if not cbody:
result.append("%s%s%s" % (" " * level, construct[0], construct[1]))
else:
result.append(" %s" % construct[0])
result.extend(cbody)
result.append(" %s" % construct[1])
return result
def GenerateNamedTypes(definitions, ancestor, element, level=1):
result = [ "componentType = namedtype.NamedTypes(" ]
result.extend(GenerateNamedTypesList(definitions, element))
result.append(")")
return result
defmap = {
'constraints' : GenerateConstraints,
'namedValues' : GenerateNamedValues,
'namedTypes' : GenerateNamedTypes,
}
def GenerateClassDefinition(definition, name, ancestor, element, level=1):
result = []
for defkey, defval in definition.items():
if defval:
fn = defmap.get(defkey)
if fn:
result.extend(fn(defval, ancestor, element, level))
return [" %s" % x for x in result]
def GenerateClass(element, ancestor):
name = element["name"]
top = "class %s(%s):" % (name, ancestor)
definition = element.get("definition")
body = []
if definition:
body = GenerateClassDefinition(definition, name, ancestor, element)
else:
typedef = element.get("typedef")
if typedef:
element["_d"].append(typedef["definitionType"])
body.append(" componentType = %s()" % typedef["definitionType"])
szc = element.get('sizeConstraint')
if szc:
body.extend(GenerateConstraints({ 'sizeConstraint' : szc }, ancestor, element))
if not body:
body.append(" pass")
TypeDeps[name] = list(frozenset(element["_d"]))
return "\n".join([top] + body)
StaticMap = {
"Null" : "univ.Null",
"Enum" : "univ.Enumerated",
"OctetString" : "univ.OctetString",
"IA5String" : "char.IA5String",
"Set" : "univ.Set",
"Sequence" : "univ.Sequence",
"Choice" : "univ.Choice",
"SetOf" : "univ.SetOf",
"BitString" : "univ.BitString",
"SequenceOf" : "univ.SequenceOf",
}
def StaticConstructor(x):
x["_d"] = []
if x["defType"] == "constructed":
dt = x["definitionType"]
x["_d"].append(dt)
else:
dt = StaticMap[x["defType"]]
return GenerateClass(x, dt)
for element in pf:
TypeDefs[element["name"]] = StaticConstructor(element)
while TypeDefs:
ready = [ k for k, v in TypeDeps.items() if len(v) == 0 ]
if not ready:
x = list()
for a in TypeDeps.values():
x.extend(a)
x = frozenset(x) - frozenset(TypeDeps.keys())
print TypeDefs
raise ValueError, sorted(x)
for t in ready:
for v in TypeDeps.values():
try:
v.remove(t)
except ValueError:
pass
del TypeDeps[t]
print TypeDefs[t]
print
print
del TypeDefs[t]
这将采用具有语法的文件,类似于以下文件:
CarrierInfo ::= OCTET STRING (SIZE(2..3))
ChargeAreaCode ::= OCTET STRING (SIZE(3))
ChargeInformation ::= OCTET STRING (SIZE(2..33))
ChargedParty ::= ENUMERATED
(chargingOfCallingSubscriber (0),
chargingOfCalledSubscriber (1),
noCharging (2))
ChargingOrigin ::= OCTET STRING (SIZE(1))
Counter ::= OCTET STRING (SIZE(1..4))
Date ::= OCTET STRING (SIZE(3..4))
您需要在生成的文件顶部添加此行:
from pyasn1.type import univ, namedtype, namedval, constraint, tag, char
并将结果命名为defs.py.然后,我将一堆漂亮的打印机附加到defs(如果你没有跳过它)
import defs, parsers
def rplPrettyOut(self, value):
return repr(self.decval(value))
for name in dir(parsers):
if (not name.startswith("_")) and hasattr(defs, name):
target = getattr(defs, name)
target.prettyOut = rplPrettyOut
target.decval = getattr(parsers, name)
然后,它归结为:
def ParseBlock(self, block):
while block and block[0] != '\x00':
result, block = pyasn1.codec.ber.decoder.decode(block, asn1Spec=parserimp.defs.CallDataRecord())
yield result
如果您仍然感兴趣,我会将代码放在某个地方。事实上,无论如何我会把它放在某个地方 - 但如果你有兴趣就告诉我,我会指出你。
答案 1 :(得分:4)
答案 2 :(得分:2)
有一个ANTLR ASN.1 grammar;使用ANTLR,您应该能够从中创建ASN.1解析器。生成pyasn1的代码留作海报的练习: - )
答案 3 :(得分:2)
我有pyasn1的经验,这足以解析相当复杂的语法。语法用python结构表示,因此不需要运行代码生成器。
答案 4 :(得分:2)
我是LEPL的作者,这是一个用Python编写的解析器,你想要做的就是我的“TODO”列表中的一件事。
我不会很快这样做,但您可能会考虑使用LEPL来构建解决方案,因为:
1 - 这是一个纯粹的Python解决方案(让生活更简单)
2 - 它已经可以解析二进制数据和文本,因此您只需要使用一个工具 - 您将用于解析ASN1规范的相同解析器将用于解析二进制数据
主要缺点是:
1 - 这是一个相当新的包,所以它可能比一些人更吵,而且支持社区不是那么大
2 - 它仅限于Python 2.6及更高版本(二进制解析器仅适用于Python 3及更高版本)。
有关详细信息,请参阅 http://www.acooke.org/lepl - 特别是,对于二进制解析,请参阅手册的相关部分(我无法直接链接到它,因为Stack Overflow似乎认为我在发送垃圾邮件)
安德鲁
PS据我所知,这不是我已经开始的主要原因是ASN 1规格不是免费提供的。如果你有权访问它们,并且它不是非法的(!),那么副本将不胜感激(不幸的是我目前正在开发另一个项目,所以这仍然需要时间来实现,但它可以帮助我更快地完成这项工作...)。
答案 5 :(得分:1)
我使用asn1c完成了类似的工作,并围绕它构建Pyrex扩展。包裹的结构在3GPP TS 32.401中描述。
使用Pyrex,您可以编写一个足够厚的包装器,以便在本机Python数据类型和正确的ASN.1表示之间进行转换(包装器生成器,例如SWIG,往往不会对该类型执行复杂的操作)。我写的包装器还跟踪了底层C数据结构的所有权(例如,访问子结构,返回了一个Python对象,但没有底层数据的副本,只有参考共享)。
包装器最终以一种半自动的方式编写,但因为这是我在ASN.1中的唯一工作,所以我从来没有完全自动化代码生成的步骤。
您可以尝试使用其他Python-C包装器并执行完全自动的转换:作业会更少,但是您会将复杂性(以及重复的容易出错的操作)移动到结构用户:因此我更喜欢Pyrex的方式。 asn1c绝对是个不错的选择。
答案 6 :(得分:1)
我最近创建了名为asn1tools的Python包,它将ASN.1规范编译成Python对象,可用于编码和解码消息。
>>> import asn1tools
>>> foo = asn1tools.compile_file('tests/files/foo.asn')
>>> encoded = foo.encode('Question', {'id': 1, 'question': 'Is 1+1=3?'})
>>> encoded
bytearray(b'0\x0e\x02\x01\x01\x16\x09Is 1+1=3?')
>>> foo.decode('Question', encoded)
{'id': 1, 'question': 'Is 1+1=3?'}