Code Monkey home page Code Monkey logo

asn1tools's People

Contributors

coderhuo avatar eerimoq avatar ezor1 avatar fabianeckermann avatar finndersen avatar futsch1 avatar gousaiyang avatar hurufu avatar mstmob avatar muued avatar xuhe5 avatar zoedberg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

asn1tools's Issues

Error related to parameterization changes

Since version 0.143.0 I get the following error compiling all.asn

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.7/site-packages/asn1tools/compiler.py", line 354, in compile_files
    numeric_enums)
  File "/usr/local/lib/python3.7/site-packages/asn1tools/compiler.py", line 284, in compile_dict
    numeric_enums),
  File "/usr/local/lib/python3.7/site-packages/asn1tools/codecs/ber.py", line 1643, in compile_dict
    return Compiler(specification, numeric_enums).process()
  File "/usr/local/lib/python3.7/site-packages/asn1tools/codecs/compiler.py", line 186, in process
    self.pre_process()
  File "/usr/local/lib/python3.7/site-packages/asn1tools/codecs/compiler.py", line 234, in pre_process
    module_name)
  File "/usr/local/lib/python3.7/site-packages/asn1tools/codecs/compiler.py", line 472, in pre_process_parameterization_step_1
    module_name)
  File "/usr/local/lib/python3.7/site-packages/asn1tools/codecs/compiler.py", line 544, in pre_process_parameterization_step_1_type
    del type_descriptor['parameters']
KeyError: 'parameters'

I created all.asn from files found in ts_10309603v010401p0.zip originally from here with cat EtsiTs103097Module.asn 1609Dot2/* TS102921/* > all.asn. I also had to uncomment two imports in EtsiTs102941MessagesCA.asn.
The files can also be found in the ETSI Git repository.

Issue in running the libarary after installation

$ asn1tools decode tests/files/foo.asn Question 300e0201011609497320312b313d333f

Error:

/usr/lib/python2.7/site-packages/asn1tools/parser.py:875: SyntaxWarning: Cannot combine element of type <type 'NoneType'> with ParserElement
  + actual_parameter_list)
error: no such attribute name

Please guide me to solve the issue

uper encode error (version137)

The asn file https://github.com/CoderHuo/learn-python3/blob/master/ulp.asn

ulpCompileVer2 = asn1tools.compile_files(ulp.asn, 'uper')

sessionID = {
    'setSessionID': {'sessionId': 8838, 'setId': ('imsi', b'd\x00\x00\x00\x00\x00 \xf2')},
    'slpSessionID': {
        'sessionID': b'\x00\x00@\x00',
        'slpId': ('iPAddress', ('ipv4Address', b'\x7f\x00\x00\x01'))
    }
}
lteCell = (
    'lteCell', {
        'cellGlobalIdEUTRA': {
            'plmn-Identity': {'mcc': [3, 1, 0], 'mnc': [3, 1, 0]}, 'cellIdentity': (b'4\xa3  ', 28)
        },
        'physCellId': 304,
        'trackingAreaCode': (b'\x13\x8e', 16),
        'rsrpResult': 59,
        'rsrqResult': 24,
        'tA': 1,
        'measResultListEUTRA': [
            {'physCellId': 275, 'measResult': {'rsrpResult': 45, 'rsrqResult': 14}},
            {'physCellId': 200, 'measResult': {'rsrpResult': 39, 'rsrqResult': 8}}
        ]
    }
)

lpp = {
    'lpp': True,
    'posProtocolVersionLPP': {'majorVersionField': 12, 'technicalVersionField': 4, 'editorialVersionField': 0}
}

sETCapabilitiesLpp = {
    'posTechnology': {
        'agpsSETassisted': True, 'agpsSETBased': True, 'autonomousGPS': False,
        'aFLT': False, 'eCID': True, 'eOTD': False, 'oTDOA': True,
        'ver2-PosTechnology-extension': {
            'gANSSPositionMethods': [{
                'ganssId': 4,
                'gANSSPositioningMethodTypes': {
                    'setAssisted': True, 'setBased': True, 'autonomous': True
                },
                'gANSSSignals': (b'\x80', 1)
            }]
        }
    },
    'prefMethod': 'noPreference',
    'posProtocol': {'tia801': False, 'rrlp': False, 'rrc': False, 'ver2-PosProtocol-extension': lpp}
}

lppPayload_0 = b'\x92+\x081\xe2\x00]\x00\x82\x17@\'\x04\x88"\x1b\x80\x00-\xe4\x00\x00A\x88<\t$0D\x18\xb3\x18f\x8f\xc0\x03$\x01\x01'
lppPayload_1 = b'\x92,\x10bb\x13\x104\xa3 &\xa4\x01@\x84\x00\x00\x00\x00\x01A \x02\x00\x00\x00\x00'
# message
suplPosInit = {
    'length': 162,
    'version': {'maj': 2, 'min': 0, 'servind': 0},
    'sessionID': sessionID,
    'message': (
        'msSUPLPOSINIT', {
            'sETCapabilities': sETCapabilitiesLpp,
            'locationId': {'cellInfo': ('ver2-CellInfo-extension', lteCell), 'status': 'current'},
            'sUPLPOS': {'posPayLoad': ('ver2-PosPayLoad-extension', {'lPPPayload': [lppPayload_0, lppPayload_1]})},
            'ver': (b'R\x88\xec\xab\xa97\\N', 64)
        }
    )
}

suplPos = {
    'length': 111,
    'version': {'maj': 2, 'min': 0, 'servind': 0},
    'sessionID': sessionID,
    'message': ('msSUPLPOS', {'posPayLoad': ('ver2-PosPayLoad-extension', {'lPPPayload': [lppPayload_1]})})
}


sendSuplPosInit = ulpCompileVer2.encode(ulpPdu, suplPosInit)
print(sendSuplPosInit)

print(binascii.hexlify(sendSuplPosInit))
print(ulpCompileVer2.decode(ulpPdu, sendSuplPosInit))

Error: asn1tools.codecs.OutOfDataError: message: sUPLPOS: posPayLoad: lPPPayload: out of data at bit offset 868 (108.4 bytes)

Value error: time data '201801221329' does not match format '%Y%m%H%M%S.%f'

Was getting this message

Value error: time data '201801221329' does not match format '%Y%m%H%M%S.%f'

when running some asn1 through a python program using asn1tools.
Part of the traceback was "~/site-packages/asn1tools/codecs/__init__.py", line 220, in generalized_time_to_datetime, so I amended the if else to include a test for string length of 13
and date = datetime.strptime([string[:-1], '%Y%m%H%M')

This worked.

This was happening because the timestamp was exactly on the minute, and so did not include seconds.

Error when compiling asn files with empty IMPORTS

I'm trying to use asn1tool with the ASN1 definitions of ETSI ITS.

asn1defs=[
'asn1/ITS-Container/ITS-Container.asn',
'asn1/CAM/CAM.asn',
'asn1/DENM/DENM.asn',
'asn1/IS/IVI_ISO_TS_14816.asn',
'asn1/IS/IVI_ISO_TS_14906.asn',
'asn1/IS/IVI_ISO_TS_17419.asn',
'asn1/IS/IVI_ISO_TS_19321.asn',
'asn1/IS/IVI_ISO_TS_24534-3.asn',
]
itsc = asn1tools.compile_files(asn1defs)

I've got an error with the asn1/IS/IVI_ISO_TS_17419.asn (trying to comment that and followings compilation is ok).

The error is:
asn1tools.parser.ParseError: Invalid ASN.1 syntax at line 918, column 1: '>!<;': Expected {{Forward: ... [{"{" "}"}]} | Forward: ...}.

The content of the file is:

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- ISO TS 17419
--
-- This document contains only the data element needed for the encoding of an IVI message
-- as defined in ISO TS 19321(2015) 
--
-- Published version location:
-- http://standards.iso.org/iso/ts/17419/
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

CITSapplMgmtIDs {iso(1) standard(0) cits-applMgmt (17419) ids (1) version1 (1)} 

DEFINITIONS AUTOMATIC TAGS::=BEGIN

IMPORTS

;

-- End of IMPORTS

-- Types

-- Variable length data types

VarLengthNumber::=CHOICE{
	content	[0]	INTEGER(0..127), -- one octet length
	extension	[1]	Ext1
	}
	
Ext1::=CHOICE{
	content	[0]	INTEGER(128..16511), -- two octets length
	extension	[1]	Ext2
}

Ext2::=CHOICE{
	content	[0]	INTEGER(16512..2113663), -- three octets length
	extension	[1]	Ext3
	}

Ext3::=INTEGER(2113664..270549119,...) -- four and more octets length
	
END

When I comment the IMPORTS and the ; with "--" everyhing is compiling.

So the problem is that asn1 is not able to handle an empty IMPORTS set.

Cannot import name WordCompleter

Hello, I just installed asn1tools but I'm unable to import the module:

# pip install asn1tools
Collecting asn1tools
  Downloading https://files.pythonhosted.org/packages/36/93/a3c1e9fb9ff06299d6cd895fc60b8774831b21c1df4161dab0b3c794c34f/asn1tools-0.124.0-py2.py3-none-any.whl (75kB)
    100% |████████████████████████████████| 81kB 309kB/s 
Requirement already satisfied: prompt-toolkit in /usr/lib/python2.7/dist-packages (from asn1tools)
Requirement already satisfied: pyparsing>=2.2.0 in /usr/lib/python2.7/dist-packages (from asn1tools)
Collecting bitstruct (from asn1tools)
  Downloading https://files.pythonhosted.org/packages/46/6f/0bcaa2c1eaf8fb7f44d5ca43d35dc677a660d3ba9050392f0df782e29e71/bitstruct-4.0.0-py2.py3-none-any.whl
Installing collected packages: bitstruct, asn1tools
Successfully installed asn1tools-0.124.0 bitstruct-4.0.0

# python
Python 2.7.15+ (default, Aug 31 2018, 11:56:52) 
[GCC 8.2.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import asn1tools
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/asn1tools/__init__.py", line 14, in <module>
    from prompt_toolkit.completion import WordCompleter
ImportError: cannot import name WordCompleter

uper encode and decode error

I found a mistake below.

fqdnAsn1 = """
ILP DEFINITIONS AUTOMATIC TAGS ::=
BEGIN
    FQDN ::= VisibleString(FROM ("a".."z" | "A".."Z" | "0".."9" |".-"))(SIZE (1..255))
END
"""

fqdn = asn1tools.compile_string(fqdnAsn1,'uper')
testdata = 'ilp.org'

data_encode = fqdn.encode('FQDN', testdata)
print(binascii.b2a_hex(data_encode))

The out print is b'07d3b382edfcb380'.
That should be b'06bb1d41d37b00'
It should be depend on "X691---- B.2 Extensibility and visibility of constraints in PER".

How to access named integers and enums by name

Question/Enhancement.

Is there any way how to refer to named integers and enums by name when asn1tools.compile_files(...) is used?

It would be great if the names were part of the compiled types.

Illustrative example of an ASN.1 specification with named integers:

Foo DEFINITIONS ::= BEGIN

    Constants ::= INTEGER  {
        min     (-1),
        max     (1),
        unknown (2)
    } (-1..2)

    SomeDays ::= ENUMERATED {
	monday(0),
	tuesday(1)
    }

END

hello, I have a few questions to ask

test_per.py:
test_s1ap_14_4_0(self) is not success.
does this tool not support all of the asn1 rule?

test_rrc_8_6_0 decode is not success.
some of type's encode/decode is not supported?

EncodeError("expected tuple, but got '{}'".format(data))

For some reason, we are facing below issue earlier it was working fine.

Question to encode: {'aTCmessageheader': {'timestamp': {'timehours': 10, 'timeminutes': 57, 'timeseconds': 8}, 'msgreferencenumber': 1, 'msgidentificationnumber': 1}, 'aTCuplinkmsgelementid': {'uM163ICAOfacilitydesignationTp4table': {'tp4table': 'labelA', 'iCAOfacilitydesignation': 'GDTA'}}}

Please let me know if you need asn file. I will share via email
Traceback (most recent call last):
File "fans_cr1_messages_encode.py", line 103, in
encoded = foo.encode('ATCuplinkmessage', atcuplinkmessage)
File "/usr/lib/python2.7/site-packages/asn1tools/compiler.py", line 100, in encode
return self._types[name].encode(data, **kwargs)
File "/usr/lib/python2.7/site-packages/asn1tools/codecs/uper.py", line 1246, in encode
self._type.encode(data, encoder)
File "/usr/lib/python2.7/site-packages/asn1tools/codecs/uper.py", line 471, in encode
self.encode_root(data, encoder)
File "/usr/lib/python2.7/site-packages/asn1tools/codecs/uper.py", line 483, in encode_root
self.encode_member(member, data, encoder)
File "/usr/lib/python2.7/site-packages/asn1tools/codecs/uper.py", line 539, in encode_member
member.encode(data[name], encoder)
File "/usr/lib/python2.7/site-packages/asn1tools/codecs/uper.py", line 1015, in encode
raise EncodeError("expected tuple, but got '{}'".format(data))
asn1tools.codecs.EncodeError: expected tuple, but got '{'uM163ICAOfacilitydesignationTp4table': {'tp4table': 'labelA', 'iCAOfacilitydesignation': 'GDTA'}}'

CompileError for 3GPP TS 38.473

Hi,
I'm trying to compile asn file define in 3gpp spec TS 38.473. Result of this is such error:

File "C:\Python27\lib\site-packages\asn1tools\codecs\compiler.py", line 628, in lookup_type_descriptor return self.lookup_in_modules('types', 'type', type_name, module_name) File "C:\Python27\lib\site-packages\asn1tools\codecs\compiler.py", line 623, in lookup_in_modules module_name)) asn1tools.errors.CompileError: Type 'OpenType' not found in module 'F1AP-Containers'.

Is this error releated with one of limitations mentioned in README? or i'm doing something wrong
F1AP.zip

Support for SAE J2735?

I am trying to compile ASN.1 Schema provided by SAE J2735.
I am getting below error:

>>>import asn1tools
 >>>foo = asn1tools.compile_files("J2735.ASN")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/site-packages/asn1tools/compiler.py", line 243, in compile_files
    return compile_dict(parse_files(filenames),
  File "/usr/lib/python2.7/site-packages/asn1tools/parser.py", line 1707, in parse_files
    return parse_string(string)
  File "/usr/lib/python2.7/site-packages/asn1tools/parser.py", line 1684, in parse_string
    e.msg))
asn1tools.parser.ParseError: Invalid ASN.1 syntax at line 140, column 36: 'TestExtension >!<{{REGION.Reg-TestMessage}} OPTIONAL,': Expected "}".

Snippet from ASN.1

TestMessage::= SEQUENCE {
   -- Part I, Sent at all times with each message
   coreData      TestcoreData,

   -- Part II Content
   partII        SEQUENCE (SIZE(1..8)) OF
                 PartIIcontent {{ partIIExtension }} OPTIONAL,

   regional      SEQUENCE (SIZE(1..4)) OF
                TestExtension {{REGION.Reg-TestMessage}} OPTIONAL,
   ...
   }

Encoding mismatch with other library

ASN.1 specification:

Sorry for raising series of issues.

The encoded reference value from playground link (whose value is same as our simulator value)and encoded value from this library are not matching. When i try to decode the encoded value from this library on below link it gives below response which is not the value which i have passed as input.
Link : http://asn1-playground.oss.com/
Encoded Reference value from playbround link :6082F9E8A906A9169D4933A380

Input : {
'aTCmessageheader': {
'timestamp': {
'timehours': 15,
'timeminutes': 39,
'timeseconds': 40
},
'msgreferencenumber': 1,
'msgidentificationnumber': 1
},
'aTCuplinkmsgelementid': {
'uM169Freetext': 'TESTING'
}
}
UPER:
Encoded: 6082f9e8a907a9169d4933a380 (13 bytes)
Decoded using this library : {'aTCmessageheader': {'timestamp': {'timehours': 15, 'timeminutes': 39, 'timeseconds': 40}, 'msgreferencenumber': 1, 'msgidentificationnumber': 1}, 'aTCuplinkmsgelementid': {'uM169Freetext': u'TESTING'}}

Decoded value after passing encoded value from this library on playground link:
rec1value ATCuplinkmessage ::= { aTCmessageheader { msgidentificationnumber 1, msgreferencenumber 1, timestamp { timehours 15, timeminutes 39, timeseconds 40 } }, aTCuplinkmsgelementid uM169Freetext : **{"TESTING",{0,0}}** }
Can you please help me in correcting the issue.

Uper encoding failed with 'Odd-length string error"

In our .asn file has a field defined ids SEQUENCE SIZE(1..10) OF UTF8String (SIZE(1..32))

but when we provide input as "ids:[]" it throws an error saying "Odd-length string" instead of expecting sequence size should be > 1

Error while parsing recursive ASN.1 specification

I'm trying to parse the following recursive specification.

Example DEFINITIONS AUTOMATIC TAGS ::= BEGIN

Query ::= CHOICE {
  con Constraint,
  exp Expression
}

Constraint ::= SEQUENCE {
    operator  ENUMERATED {
      eq (0), ne (1), lt (2),
      le (3), gt (4), ge (5)
    },
    value     Value
}

Expression ::= SEQUENCE {
  operator  ENUMERATED { and (0), or (1) },
  left      Query,
  right     Query
}

Value ::= CHOICE {
  source  Entity,
  target  Entity,
  date    BinaryTime,
  service Service
}

Entity ::= PrintableString

Service ::= PrintableString

BinaryTime ::= INTEGER

END

When I run the compile command, I get an error.

$ compile messages.asn
error: cannot convert 'NoneType' object to bytes

Any help would be greatly appreciated.

decode functions PER

Dear eerimoq,

I'd like to use your tool for PER encoding/decoding. Do you know when the corresponding functions will be implemented?
Are you still working on it?

Thanks in advance

the open function in parse_files should include encoding type

eg:

def parse_files(filenames,encoding=None):
    """Parse given ASN.1 specification file(s) and return a dictionary of
    its/their contents.

    >>> foo = asn1tools.parse_files('foo.asn')

    """

    if isinstance(filenames, str):
        filenames = [filenames]

    string = ''

    for filename in filenames:
        with open(filename, 'r',encoding=encoding) as fin:
            string += fin.read()
            string += '\n'

    return parse_string(string)

asn1tools.codecs.EncodeError: enumeration value

I'm facing below error when im trying to pass to enumerated value.
`
ASN.1 specification:

-- A simple protocol taken from Wikipedia.

Foo DEFINITIONS ::= BEGIN

Question ::= SEQUENCE {
    id        Tp4table,
    question  IA5String
}

Answer ::= SEQUENCE {
    id        INTEGER,
    answer    BOOLEAN
}

    Tp4table ::= ENUMERATED
    {
    labelA  (0),
    labelB  (1)
    }

END`

Input : question = {'id': 1, 'question': 'What is this problem'}

Error :asn1tools.codecs.EncodeError: enumeration value '1' not found in ['labelA', 'labelB']

Accessing constants by name when assigning field values

Hello!
I have such a question.
I have a module:

Foo DEFINITIONS ::= BEGIN
    defID0 INTEGER ::= 0
    defID1 INTEGER ::= 1
    IDType ::= INTEGER (defID0 | defID1)
    Answer ::= SEQUENCE {
        id        IDType,
        answer    BOOLEAN
    }

END

and I try to create an instance of Answer and assign id field a constant value:
m.encode("Answer",{'id':'defID0','answer':1})
and I get such an error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/asn1tools/compiler.py", line 75, in encode
    return self._types[name].encode(data)
  File "/usr/local/lib/python2.7/dist-packages/asn1tools/codecs/der.py", line 953, in encode
    self._type.encode(data, encoded)
  File "/usr/local/lib/python2.7/dist-packages/asn1tools/codecs/der.py", line 325, in encode
    member.encode(value, encoded_members)
  File "/usr/local/lib/python2.7/dist-packages/asn1tools/codecs/der.py", line 198, in encode
    encoded.extend(encode_signed_integer(data))
  File "/usr/local/lib/python2.7/dist-packages/asn1tools/codecs/der.py", line 120, in encode_signed_integer
    encoded.append(data & 0xff)
TypeError: unsupported operand type(s) for &: 'str' and 'int'

Is it possible to use constants defined in my module to assign field values?

Thank you in advance.

PS In my test, I was using DER encoder

Import of import not supported

Compiling import.asn

A
DEFINITIONS AUTOMATIC TAGS ::= BEGIN

    EXPORTS ALL;

    Type ::= INTEGER

END

B
DEFINITIONS AUTOMATIC TAGS ::= BEGIN 

    IMPORTS 

        Type FROM A

    ;

    AnotherType ::= Type

END

C
DEFINITIONS AUTOMATIC TAGS ::= BEGIN 

    IMPORTS 

        Type FROM B

    ;

    AndAnotherType ::= Type

END

gives me asn1tools.errors.CompileError: Type 'Type' imported by module 'C' not found in module 'B'.

Comment markers not supported

Compiling comment.asn

/*
  This is a multi-line comment.
*/

gives me asn1tools.parser.ParseError: Invalid ASN.1 syntax at line 1, column 1: '>!</*': Expected modulereference.

Decoding error

Hello!

I'm trying to use this decoder for ber decoding. Binary data in the file below. This file contents asn1 binary data which were encoded by asn1c library. It's decoded by https://lapo.it/asn1js/ perfectly. But when I tried use your library I get error "expected SEQUENCE with tag 0x30 but got 0x80"
dump.txt

Asn1 stucture file

structure.txt

can xer.py CompileType dump XML tags for ASN definitions.

Is it possible to enhance the xer.py CompileType dump the XML tree w.r.t to any module ?
like say dumpxml() method which will print below asn as -

PersonData-Module DEFINITIONS AUTOMATIC TAGS ::=
BEGIN
Person-Info ::= SEQUENCE {
    person-name   [0] IMPLICIT VisibleString (SIZE(0..64)),
    person-id  [1] IMPLICIT VisibleString (SIZE(16..36)),
    person-type     [2] IMPLICIT ENUMERATED {
        e-man(0),
        e-woman(1),
        e-boy(2),
        e-girl(3),
        ...
    },
    person-last-ids    [3] IMPLICIT SEQUENCE (SIZE(1..3)) OF OCTET STRING (SIZE(4..16)),
    ...
}
END

printed as below or similar ..... if the same is printed in JSON it can be converted to XML

<Person-Info>
    <person-name>VisibleString</person-name>
    <person-id>VisibleString</person-id>
    <person-type><e-man/></person-type>
    <person-last-ids>octect</person-last-ids>
</Person-Info>

UPER decode error when using REAL and extension marker

I believe I found a bug when decoding a structure containing a REAL and extension marker using UPER:

Python 2.7.14 (default, Oct 31 2017, 21:12:13)
[GCC 6.4.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import asn1tools
>>> asn = """
... Test DEFINITIONS ::= BEGIN
...     Test ::= SEQUENCE
...     {
...         value   REAL,
...         ...
...     }
... END
... """
>>> uper = asn1tools.compile_string(asn, codec = 'uper')
>>> encoded = uper.encode("Test", {'value': 120})
>>> uper.decode("Test", encoded)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/site-packages/asn1tools/compiler.py", line 163, in decode
    decoded = type_.decode(data)
  File "/usr/lib/python2.7/site-packages/asn1tools/codecs/uper.py", line 288, in decode
    return self._type.decode(decoder)
  File "/usr/lib/python2.7/site-packages/asn1tools/codecs/per.py", line 816, in decode
    decoded = self.decode_root(decoder)
  File "/usr/lib/python2.7/site-packages/asn1tools/codecs/per.py", line 832, in decode_root
    value = member.decode(decoder)
  File "/usr/lib/python2.7/site-packages/asn1tools/codecs/per.py", line 1095, in decode
    return decode_real(decoder.read_bytes_aligned(length))
  File "/usr/lib/python2.7/site-packages/asn1tools/codecs/ber.py", line 313, in decode_real
    decoded = decode_real_decimal(data)
  File "/usr/lib/python2.7/site-packages/asn1tools/codecs/ber.py", line 299, in decode_real_decimal
    return float(data[1:])
ValueError: could not convert string to float: ▒▒

Can we create an ordered dictionary instead of normal dictionary when it's decoded?

>>> import asn1tools
>>> foo = asn1tools.compile_files('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?'}

Can we create an ordered dictionary instead of normal dictionary when we decode?

struct.error: required argument is not an integer

Hi!

Trying to run the following code but I got the following error.

File "EnrolementCredential.py", line 49, in <module>
    'signature' : ('ecdsaNistP256Signature', { 'r' : ('x-only' , xstr2_EC), 's' : ystr2_EC})
struct.error: required argument is not an integer

I got the same error if I delete the optional signature value (the last row in my code down below).
I used the same values by pyasn1 but should change because of the COER encoding.

This is the ASN.1 implementation

ToBeSignedCertificate ::=
        SEQUENCE {  id                      CertificateId,
                    cracaId                 HashedId3,
                    crlSeries               CrlSeries,
                    validityPeriod          ValidityPeriod,
                    region                  GeographicRegion OPTIONAL,
                    assuranceLevel          SubjectAssurance OPTIONAL,
                    appPermissions          SequenceOfPsidSsp OPTIONAL,
                    certIssuePermissions    SequenceOfPsidGroupPermissions OPTIONAL,
                    certRequestPermissions  SequenceOfPsidGroupPermissions OPTIONAL,
                    canRequestRollover      NULL OPTIONAL,
                    encryptionKey           PublicEncryptionKey OPTIONAL,
                    verifyKeyIndicator      VerificationKeyIndicator,
                    ...
}

This is my code:

#EneolementCredential

import asn1tools
import datetime, calendar, time
from Crypto.PublicKey import ECC

issuerid  = bytes.fromhex('0101010101010101') #Example value
cracaId   = bytes.fromhex('020202') # Identifies the Certificate Revocation Authorization CA (example)
crlSeries = 5 #Example value

t = (2004, 1, 1, 0, 0, 0, 3, 1, 0) # TAI time type secs from this moment
generation_time = calendar.timegm(time.gmtime())-time.mktime(t)
#duration
duration_type = 'hours' # My choice
in_hours      = 8761 #One year (example)


f = open('myprivatekey.der','rb')
EC_key = ECC.import_key(f.read())
f.close()

x_EC = EC_key.pointQ.x  # x and y key point conversation
y_EC = EC_key.pointQ.y

xstr1_EC = str(hex(int(x_EC)))
xstr2_EC = bytes.fromhex(xstr1_EC[2:66])
ystr1_EC = str(hex(int(y_EC)))
ystr2_EC = bytes.fromhex(ystr1_EC[2:66])

xstr2_EC = b'0808080808080808080808080808080808080808080808080808080808080808'
ystr2_EC = b'0808080808080808080808080808080808080808080808080808080808080808'

Certificate = asn1tools.compile_files('EtsiTs102941MessagesItss.asn',codec='oer')

encoded = Certificate.encode('CertificateBase',{
                                                'version'   : 3,
                                                'type'      : 'explicit',
                                                'issuer'    : ('sha256AndDigest', issuerid),
                                                'toBeSigned':   {
                                                                    'id'                : ('none', ''), #Possibly none
                                                                    'cracaId'           : cracaId,
                                                                    'crlSeries'         : crlSeries,
                                                                    'validityPeriod'    :   {
                                                                                                'start'     : generation_time,
                                                                                                'duration'  : (duration_type, in_hours)
                                                                                            },
                                                                    'verifyKeyIndicator': ('verificationKey' , ('ecdsaNistP256' , ('uncompressed', {'x' : xstr2_EC  , 'y' : ystr2_EC})))
                                                                },
                                                'signature' : ('ecdsaNistP256Signature', { 'r' : ('x-only' , xstr2_EC), 's' : ystr2_EC})
                                               }
                            )

Using the ASN.1 code of the Ieee1609.2 standard

I am newbie at ASN.1. I do something wrong or something else is the problem? The COER encoding or the '...' part could be the problem?

BIT STRING SIZE extension encode error

The asn file like this:

import asn1tools

def printBin(bya):
    for i in bya:
        strByte = '{:0>8}'.format(bin(i)[2:])
        strByte2 = '{} {}'.format(strByte[0:4], strByte[4:8])
        print(strByte2, end='| ')
    print()

print("hello")
l_strASN = """
Foo DEFINITIONS ::= BEGIN

TransportLayerAddress ::= BIT STRING (SIZE(1..160, ...))

END
"""
print(l_strASN)
foo = asn1tools.compile_string(l_strASN, 'per')

l_strTypeName = 'TransportLayerAddress'

encoded = foo.encode(l_strTypeName, (b'\xff', 1))
print("encoded:", encoded.hex())
printBin(encoded)
decoded = foo.decode(l_strTypeName, encoded)
print("decoded:", decoded, '\n')

encoded = foo.encode(l_strTypeName, (b'\xff', 2))
print("encoded:", encoded.hex())
printBin(encoded)
decoded = foo.decode(l_strTypeName, encoded)
print("decoded:", decoded, '\n')

encoded = foo.encode(l_strTypeName, (b'\xff', 3))
print("encoded:", encoded.hex())
printBin(encoded)
decoded = foo.decode(l_strTypeName, encoded)
print("decoded:", decoded, '\n')

The output is:

encoded: 0080
0000 0000| 1000 0000| 
decoded: (b'\x80', 1)

encoded: 01c0
0000 0001| 1100 0000|
decoded: (b'\xc0', 2)

encoded: 02e0
0000 0010| 1110 0000| 
decoded: (b'\xe0', 3)

It seem that the BIT STRING SIZE extension bit is omitted.

It should be encoded like this:(x for aligned)

0000 0000| 0xxx xxxx| 1xxx xxxx| 
decoded: (b'\x80', 1)

0000 0000| 1xxx xxxx| 11xx xxxx| 
decoded: (b'\xc0', 2)

0000 0001| 0xxx xxxx| 111x xxxx| 
decoded: (b'\xe0', 3)

Please help to check if there is any problem.
Thank you.

UTF8String with uper

hello Eric,I encounter an issue when encoding UTF8String with uper and checkConstaints=True, it throws error
"Encode Error installationorder:uuid:Expected a Character in ' ',but got 'v'(0x76)."
I debugged and find "permitted_alphabet" in constaints_checker.py is ' ', can you help me with the issue? lots of thanks.

PER cannot decode CHOICE

The PER decoder does not seem to be able to handle CHOICE. Encoding goes fine.
I have this toy-specification called asn1.asn :

Foo DEFINITIONS ::= BEGIN
    MyChoice ::= CHOICE {
            c1   NULL,
            c2   INTEGER,
            c3   INTEGER
    }
END

My test code looks like:

import asn1tools
foo = asn1tools.compile_files('asn1.asn', codec='per')
encoded = foo.encode('MyChoice', ('c2',5)) # this goes fine
decoded = foo.decode('MyChoice',encoded) # this fails in per.py

Error trace:

Traceback (most recent call last):
  File "/Users/mats/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/173.4674.37/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1668, in <module>
    main()
  File "/Users/mats/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/173.4674.37/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1662, in main
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/Users/mats/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/173.4674.37/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1072, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/Projects/asn1test/mymain.py", line 115, in <module>
    decoded = foo.decode('MyChoice',encoded)
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/asn1tools/compiler.py", line 116, in decode
    return self._types[name].decode(data)
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/asn1tools/codecs/per.py", line 820, in decode
    return self._type.decode(decoder)
TypeError: decode() takes exactly 3 arguments (2 given)

compatible with marben

Hello,do you know whether asn1tool is compatible with marben, if don't, how to make asn1tool can decode bytearray which is generated by marben?

How to use parse_files for filling the values of the keys in the dictionary

My requirement is to create a dictionary based on the asn file and then fill the key's value using an excel sheet, and then later encode/decode .Currently I'm manually creating the desired output and filling its values from the excel sheet, Now for the below schema, Is the Parsed output and desired output both same?if both are same how do we fill values for the keys inside a dictionary? If not how to make the parser output equivalent to desired output?Any recommendations would be highly helpful.

Module-order DEFINITIONS AUTOMATIC TAGS ::=

BEGIN

Order ::= SEQUENCE {

header Order-header

}

Order-header ::= SEQUENCE {

reference NumericString (SIZE (12)),

date NumericString (SIZE (8)) -- MMDDYYYY --

}END

Parser Output

        foo = asn1tools.parse_files('we.asn')

        foo

{'Module-order': {'extensibility-implied': False, 'tags': 'AUTOMATIC', 'imports': {}, 'object-sets': {}, 'values': {}, 'object-classes': {}, 'types': {'Order': {'type': 'SEQUENCE', 'members': [{'type': 'Order-header', 'name': 'header'}]}, 'Order-header': {'type': 'SEQUENCE', 'members': [{'type': 'NumericString', 'name': 'reference', 'size': [12]}, {'type': 'NumericString', 'name': 'date', 'size': [8]}]}}}}

{header:{reference:NumericString (SIZE (12)),date NumericString (SIZE (8)) -- MMDDYYYY --}}

Desired Output

{'header':{'reference': NumericString,'date':NumericString}}

ALL EXCEPT not supported

Compiling except.asn

Foo DEFINITIONS ::= BEGIN

    Enum ::= ENUMERATED {
        bar(0),
        ...
    }

    Sequence ::= SEQUENCE {
        foo Enum,
        ...
    }
    (
        WITH COMPONENTS { foo (bar) } |
        WITH COMPONENTS { foo (ALL EXCEPT bar) }
    )

END

gives me asn1tools.parser.ParseError: Invalid ASN.1 syntax at line 14, column 36: 'WITH COMPONENTS { foo (ALL >!<EXCEPT bar) }': Expected ")".

extension encode error

I am a new pythoner to ues the asn1tools in python3.65 enviroment.
I found a mistake below.

foo = '''
Foo DEFINITIONS ::= BEGIN

    PosProtocol ::= SEQUENCE {
        tia801  BOOLEAN,
        rrlp    BOOLEAN,
        rrc     BOOLEAN,
        ...,
        ver2-PosProtocol-extension Ver2-PosProtocol-extension
    }

    Ver2-PosProtocol-extension ::= SEQUENCE {
        lpp     BOOLEAN,
        posProtocolVersionRRLP   PosProtocolVersion3GPP  OPTIONAL,
        ...,
        lppe          BOOLEAN OPTIONAL}

    PosProtocolVersion3GPP ::= SEQUENCE {
        majorVersionField      INTEGER(0..255),
        technicalVersionField  INTEGER(0..255),
        editorialVersionField  INTEGER(0..255),
        ...}
END
'''

testdata = {
    'tia801': False,
    'rrlp': True,
    'rrc': False,
    'lpp': False,
   #ver2-PosProtocol-extension: {
    'posProtocolVersionRRLP': {
        'majorVersionField': 7,
        'technicalVersionField': 11,
        'editorialVersionField': 0
    }
    #}
}
t1 = asn1tools.compile_string(foo, 'uper')
t1_encode = t1.encode('PosProtocol', testdata)
print(binascii.b2a_hex(t1_encode))

t2_decode = t1.decode('PosProtocol', t1_encode)
print(t2_decode)

The first output is b'a010480e160000'
then I decode the t1_encode, but the decode result is wrong.
The second output is {'tia801': False, 'rrlp': True, 'rrc': False, 'lpp': False, 'lppe': False} , not same as the testdata .
So I look the source code , may be the encode_additions function have same mistakes.
but it's difficult to me to find the root cause.

Thank you.

compile ieee1609_2.asn fail: Value 'unknown' not found in module 'IEEE1609dot2BaseTypes'

Hello Folks,
I tried to compile ieee1609_2.asn listed in asn1tools/tree/master/tests/files/ieee.
Got error: Value 'unknown' not found in module 'IEEE1609dot2BaseTypes'

import asn1tools
oer = asn1tools.compile_files('ieee1609_2.asn', 'oer')
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python27\lib\site-packages\asn1tools\compiler.py", line 331, in compile_files
    any_defined_by_choices)
  File "C:\Python27\lib\site-packages\asn1tools\compiler.py", line 275, in compile_dict
    return Specification(codec.compile_dict(specification),
  File "C:\Python27\lib\site-packages\asn1tools\codecs\oer.py", line 1354, in compile_dict
    return Compiler(specification).process()
  File "C:\Python27\lib\site-packages\asn1tools\codecs\compiler.py", line 122, in process
    module_name)
  File "C:\Python27\lib\site-packages\asn1tools\codecs\oer.py", line 1180, in process_type
    module_name)
  File "C:\Python27\lib\site-packages\asn1tools\codecs\oer.py", line 1306, in compile_type
    module_name)
  File "C:\Python27\lib\site-packages\asn1tools\codecs\compiler.py", line 682, in set_compiled_restricted_to
    module_name))
  File "C:\Python27\lib\site-packages\asn1tools\codecs\compiler.py", line 561, in get_restricted_to_range
    minimum = self.lookup_value(minimum, module_name)[0]['value']
  File "C:\Python27\lib\site-packages\asn1tools\codecs\compiler.py", line 630, in lookup_value
    return self.lookup_in_modules('values', 'value', value_name, module_name)
  File "C:\Python27\lib\site-packages\asn1tools\codecs\compiler.py", line 622, in lookup_in_modules
    module_name))
asn1tools.errors.CompileError: Value 'unknown' not found in module 'IEEE1609dot2BaseTypes'

Replace pyparsing with faster parser

pyparsing is easy to use, but it is very slow. Parsing a fairly big ASN.1 specification takes a noticeable amount of time.

Possibly replace with lark, or any other fast and easy to use parser.

Does it support 3gpp Release15 36423-f00.doc ?

Does it support 3gpp Release15 36423-f00.doc ?
I take the errors as follow when i call asn1tools.compile_files interface.

Traceback (most recent call last):
  File "E:\workspace\web_flask\asn1_coder.py", line 14, in <module>
    g_asn1_table = asn1tools.compile_files(os.path.join(g_base_dir, '36423-f00.asn'), 'per')
  File "D:\DevTools\Python36\lib\site-packages\asn1tools\compiler.py", line 245, in compile_files
    any_defined_by_choices)
  File "D:\DevTools\Python36\lib\site-packages\asn1tools\compiler.py", line 211, in compile_dict
    return Specification(codec.compile_dict(specification),
  File "D:\DevTools\Python36\lib\site-packages\asn1tools\codecs\per.py", line 1755, in compile_dict
    return Compiler(specification).process()
  File "D:\DevTools\Python36\lib\site-packages\asn1tools\codecs\compiler.py", line 65, in process
    module_name)
  File "D:\DevTools\Python36\lib\site-packages\asn1tools\codecs\per.py", line 1532, in process_type
    module_name)
  File "D:\DevTools\Python36\lib\site-packages\asn1tools\codecs\per.py", line 1571, in compile_type
    flat_additions=True))
  File "D:\DevTools\Python36\lib\site-packages\asn1tools\codecs\per.py", line 1678, in compile_members
    compiled_members)
  File "D:\DevTools\Python36\lib\site-packages\asn1tools\codecs\per.py", line 1710, in compile_root_member
    module_name)
  File "D:\DevTools\Python36\lib\site-packages\asn1tools\codecs\per.py", line 1716, in compile_member
    module_name)
  File "D:\DevTools\Python36\lib\site-packages\asn1tools\codecs\per.py", line 1643, in compile_type
    module_name))
  File "D:\DevTools\Python36\lib\site-packages\asn1tools\codecs\per.py", line 1545, in compile_type
    module_name))
  File "D:\DevTools\Python36\lib\site-packages\asn1tools\codecs\per.py", line 1678, in compile_members
    compiled_members)
  File "D:\DevTools\Python36\lib\site-packages\asn1tools\codecs\per.py", line 1710, in compile_root_member
    module_name)
  File "D:\DevTools\Python36\lib\site-packages\asn1tools\codecs\per.py", line 1716, in compile_member
    module_name)
  File "D:\DevTools\Python36\lib\site-packages\asn1tools\codecs\per.py", line 1643, in compile_type
    module_name))
  File "D:\DevTools\Python36\lib\site-packages\asn1tools\codecs\compiler.py", line 332, in lookup_type_descriptor
    module_name))
asn1tools.errors.CompileError: Type 'X2AP-ELEMENTARY-PROCEDURE.&procedureCode' not found in module 'X2AP-PDU-Descriptions'.

36423-f00.txt

Named constants not supported

Compiling constant.asn

Foo DEFINITIONS ::= BEGIN

    Constants ::= INTEGER  {
        min     (-1),
        max     (1),
        unknown (2)
    } (-1..2)

    A ::= Constants (min..max)
    B ::= Constants (unknown)

END

gives me asn1tools.errors.CompileError: Value 'min' not found in module 'Foo'.

Installation from sources fails

I tried to install the package using the following command:

pip install --no-binary :all: asn1tools

It failed with the following backtrace:

Collecting asn1tools
  Using cached asn1tools-0.43.0.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-do00dtb9/asn1tools/setup.py", line 4, in <module>
        import asn1tools
      File "/tmp/pip-build-do00dtb9/asn1tools/asn1tools/__init__.py", line 11, in <module>
        from .compiler import compile_dict
      File "/tmp/pip-build-do00dtb9/asn1tools/asn1tools/compiler.py", line 6, in <module>
        from .parser import parse_files
      File "/tmp/pip-build-do00dtb9/asn1tools/asn1tools/parser.py", line 8, in <module>
        from pyparsing import Literal
    ImportError: No module named 'pyparsing'
    
    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-do00dtb9/asn1tools/

The problem seems to come from the fact that you import asn1tools in the setup script.

Are there plans to support parameterization?

The following is in my ASN file:

SetupRelease { ElementTypeParam } ::= CHOICE {
    release         NULL,
    setup           ElementTypeParam
}
LocationMeasurementIndication-IEs ::=       SEQUENCE {
    measurementIndication       SetupRelease { LocationMeasurementInfo},
    nonCriticalExtension        SEQUENCE{}                               OPTIONAL
}

$ compile -i per 331.asn
error: Type 'ElementTypeParam' not found in module 'NR-RRC-Definitions'.

Invalid ASN.1 syntax error

I just started with ASN.1 and wanted to use asn1tools.
The attached file (concatenated according to this) causes asn1tools.parser.ParseError: Invalid ASN.1 syntax at line 287, column 68: 'EndEntityType ::= BIT STRING {app (0), enrol (1) } (SIZE (8)) (ALL >!<EXCEPT {})': Expected ")".
If I just remove that line I get asn1tools.parser.ParseError: Invalid ASN.1 syntax at line 1439, column 23: 'RecipientInfo >!<(WITH COMPONENTS {': Expected ")".
http://asn1-playground.oss.com/ does not complain. Is the asn file not correct?
scms.asn.txt

TypeError: Object of type 'bytes' is not JSON serializable

>>> decoded = g_asn1_table.decode(msg_type, data_bytes)
>>>  print(decoded )
{'message': {'dl-Bandwidth': 'n15', 'phich-Config': {'phich-Duration': 'normal', 'phich-Resource': 'oneSixth'}, 'systemFrameNumber': (b'\x00', 8), 'spare': (b'\x8c@', 10)}}
>>> json.dumps(decoded, indent=4)
TypeError: Object of type 'bytes' is not JSON serializable

JSON do not support the type 'bytes', but the decode result contains the b'\x00'.
I suggest use str type for the asn1 BIT STRING type.
this is the result:

{
    "message": {
        "dl-Bandwidth": "n15",
        "phich-Config": {
            "phich-Duration": "normal",
            "phich-Resource": "oneSixth"
        },
        "systemFrameNumber": "00000000b",
        "spare": "1000110001b"
    }
}

Compiling latest ieee1609_2.asn - handling ALL EXCEPT

I tested the latest ieee1609_2.asn obtained from repository github.com/wwhyte-si/1609dot2-asn (all asn files combined into one Dot2all.asn)

Dot2all.asn.txt

Error: asn1tools.parser.ParseError: Invalid ASN.1 syntax at line 625, column 68: 'EndEntityType ::= BIT STRING {app (0), enrol (1) } (SIZE (8)) (ALL >!<EXCEPT {})': Expected ")".

Problematic line in ASN file is

EndEntityType ::= BIT STRING {app (0), enrol (1) } (SIZE (8)) (ALL EXCEPT {})
, specifically (ALL EXCEPT {}).

Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import asn1tools
>>> oer = asn1tools.compile_files('Dot2all.asn', 'oer')

Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python27\lib\site-packages\asn1tools\compiler.py", line 329, in compile_files
    return compile_dict(parse_files(filenames, encoding),
  File "C:\Python27\lib\site-packages\asn1tools\parser.py", line 1761, in parse_files
    return parse_string(string)
  File "C:\Python27\lib\site-packages\asn1tools\parser.py", line 1727, in parse_string
    e.msg))
asn1tools.parser.ParseError: Invalid ASN.1 syntax at line 625, column 68: 'EndEntityType ::= BIT STRING {app (0), enrol (1) } (SIZE (8)) (ALL >!

DER: error while encoding OCTET STRING more than 255 bytes long

When I try to encode an OCTET STRING more than 255 bytes long, I get an exception in codecs/der.py:
490: encoded.append(len(data))
because the implementation seems not to support multibyte length fields. The same must happen with other array types.

Please, mention this limitation in the lib description.

When decoding also return the number of bytes consumed

When decoding it would be useful if the number of bytes from the buffer that has been consumed is returned along with the decoded object. decode_length is not useful to me as my objects are uper encoded.

For example, asn1c has a function uper_decode_complete that returns the number of bytes consumed.

This is useful when there is other data located after the ASN.1 encoded object and the length of the ASN.1 encoded object has not been previously specified.

Invalid ASN.1 syntax parsing SEQUENCE

I am trying to compile a file with some sentences like SEQUENCE (SIZE (1..4),...), but these lines raise a ParseError.

Example:

GicPart::= SEQUENCE {
	detectionZoneIds			SEQUENCE (SIZE (1..8,...)) OF Zid OPTIONAL,
	its-Rrid				VarLengthNumber OPTIONAL,
	relevanceZoneIds		SEQUENCE (SIZE (1..8,...)) OF Zid OPTIONAL,
	direction				Direction OPTIONAL,
	driverAwarenessZoneIds	SEQUENCE (SIZE (1..8,...)) OF Zid OPTIONAL,
	minimumAwarenessTime	INTEGER (0..255) OPTIONAL,
	applicableLanes			SEQUENCE (SIZE (1..8,...)) OF LanePosition OPTIONAL,
	iviType					IviType,
	iviPurpose				IviPurpose OPTIONAL,
	laneStatus				LaneStatus OPTIONAL,
	vehicleCharacteristics	SEQUENCE (SIZE (1..8, ...)) OF CompleteVehicleCharacteristics OPTIONAL,
	driverCharacteristics	DriverCharacteristics OPTIONAL,
	layoutId				INTEGER(1..4,...) OPTIONAL,
	preStoredlayoutId		INTEGER(1..64,...) OPTIONAL,
	roadSignCodes			SEQUENCE (SIZE (1..4),...) OF RSCode,
	extraText				SEQUENCE (SIZE (1..4),...) OF Text (WITH COMPONENTS {layoutComponentId, language, textContent (SIZE(1..32))}) OPTIONAL,
	...
	}
asn1tools.parser.ParseError: Invalid ASN.1 syntax at line 91, column 50: 'roadSignCodes                   SEQUENCE >!<(SIZE (1..4),...) OF RSCode,': Expected "{".

There is the file that I want to compile, ISO19321(2015)IVIv1.asn, and his dependencies
standards.tar.gz

Multiple imports override each other

I extended the import_imported.asn test file.

-- Import imported type and value.

A DEFINITIONS AUTOMATIC TAGS ::=

BEGIN

    EXPORTS ALL;

    Type ::= INTEGER

    value Type ::= 5

END


B DEFINITIONS AUTOMATIC TAGS ::=

BEGIN

    IMPORTS

        Type,
        value
    FROM A;

    AnotherType ::= Type

    anotherValue AnotherType ::= value

END


C DEFINITIONS AUTOMATIC TAGS ::=

BEGIN

    IMPORTS

        Type,
        anotherValue
    FROM B;

    AndAnotherType ::= Type

    andAnotherValue AndAnotherType ::= anotherValue

END


D DEFINITIONS AUTOMATIC TAGS ::=

BEGIN

    IMPORTS

        Type
    FROM B
        value
    FROM B;

    AnotherType ::= Type

    anotherValue AnotherType ::= value

END

The first import Type gets overwritten by the second one value which leads to:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.7/site-packages/asn1tools/compiler.py", line 354, in compile_files
    numeric_enums)
  File "/usr/local/lib/python3.7/site-packages/asn1tools/compiler.py", line 284, in compile_dict
    numeric_enums),
  File "/usr/local/lib/python3.7/site-packages/asn1tools/codecs/ber.py", line 1621, in compile_dict
    return Compiler(specification, numeric_enums).process()
  File "/usr/local/lib/python3.7/site-packages/asn1tools/codecs/compiler.py", line 196, in process
    module_name)
  File "/usr/local/lib/python3.7/site-packages/asn1tools/codecs/ber.py", line 1430, in process_type
    module_name)
  File "/usr/local/lib/python3.7/site-packages/asn1tools/codecs/ber.py", line 1549, in compile_type
    module_name)
  File "/usr/local/lib/python3.7/site-packages/asn1tools/codecs/ber.py", line 1542, in compile_implicit_type
    module_name)
  File "/usr/local/lib/python3.7/site-packages/asn1tools/codecs/compiler.py", line 583, in compile_user_type
    module_name))
  File "/usr/local/lib/python3.7/site-packages/asn1tools/codecs/compiler.py", line 770, in lookup_type_descriptor
    return self.lookup_in_modules('types', 'type', type_name, module_name)
  File "/usr/local/lib/python3.7/site-packages/asn1tools/codecs/compiler.py", line 767, in lookup_in_modules
    module_name))
asn1tools.errors.CompileError: Type 'Type' not found in module 'D'.

TypeError: string indices must be integers when compile_file

the asn1 file link: []((https://github.com/CoderHuo/learn-python3/blob/master/LCS-AP.asn)

lcs_ap_compile = asn1tools.compile_files("LCS-AP.asn",'per')
File "C:\Users\shhuo\AppData\Local\Programs\Python\Python36\lib\site-packages\asn1tools\compiler.py", line 354, in compile_files
numeric_enums)
File "C:\Users\shhuo\AppData\Local\Programs\Python\Python36\lib\site-packages\asn1tools\compiler.py", line 284, in compile_dict
numeric_enums),
File "C:\Users\shhuo\AppData\Local\Programs\Python\Python36\lib\site-packages\asn1tools\codecs\per.py", line 2245, in compile_dict
return Compiler(specification, numeric_enums).process()
File "C:\Users\shhuo\AppData\Local\Programs\Python\Python36\lib\site-packages\asn1tools\codecs\compiler.py", line 186, in process
self.pre_process()
File "C:\Users\shhuo\AppData\Local\Programs\Python\Python36\lib\site-packages\asn1tools\codecs\compiler.py", line 234, in pre_process
module_name)
File "C:\Users\shhuo\AppData\Local\Programs\Python\Python36\lib\site-packages\asn1tools\codecs\compiler.py", line 472, in pre_process_parameterization_step_1
module_name)
File "C:\Users\shhuo\AppData\Local\Programs\Python\Python36\lib\site-packages\asn1tools\codecs\compiler.py", line 491, in pre_process_parameterization_step_1_type
module_name)
File "C:\Users\shhuo\AppData\Local\Programs\Python\Python36\lib\site-packages\asn1tools\codecs\compiler.py", line 535, in pre_process_parameterization_step_1_type
parameterized_module_name)
File "C:\Users\shhuo\AppData\Local\Programs\Python\Python36\lib\site-packages\asn1tools\codecs\compiler.py", line 574, in pre_process_parameterization_step_1_dummy_to_actual_type
module_name)
File "C:\Users\shhuo\AppData\Local\Programs\Python\Python36\lib\site-packages\asn1tools\codecs\compiler.py", line 584, in pre_process_parameterization_step_1_dummy_to_actual_type
if parameter['type'] == dummy_parameter:
TypeError: string indices must be integers

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.