vn.py 11.7 KB
Newer Older
1
2
3
4
5
6
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
    ASN.1 Value Editor - Value Notation parser and converter

Maxime Perrotin's avatar
Maxime Perrotin committed
7
    This module contains the following functions:
8
9
10
11
12
13
14
15
16

    1) fromValueNotationToPySide(varName, string)
        Parse a string containing an ASN.1 value expressed in GSER
        (also called ASN.1 Value Notation) and return a Python structure that
        is compatible with the widget of the ASN.1 Value Editor

    2) toASN1ValueNotation(val)
        Does the reverse (from Qt widget to ASN.1 Value Notation/GSER)

17
    3) valueNotationToCTypes(gser, dest, sort, ASN1Mod, ASN1_AST, var=None)
18
        Parse a Value Notation string and fill a ctypes instance with the values
Maxime Perrotin's avatar
Maxime Perrotin committed
19

20
21
22
    4) format(gser)
       properly format a GSER string. useful for comparing them

23
    Copyright (c) 2012-2018 European Space Agency
24
25
26
27
28
29
30
31

    Designed and implemented by Maxime Perrotin

    Contact: maxime.perrotin@esa.int

    License is LGPLv3 - Check the LICENSE file
"""

Maxime Perrotin's avatar
Maxime Perrotin committed
32

Maxime Perrotin's avatar
Maxime Perrotin committed
33
34
35
from pyparsing import(Word, QuotedString, Literal, Combine, Optional,
                      oneOf, OneOrMore, srange, nums, nestedExpr, Forward,
                      delimitedList, Keyword, ParseException)
Maxime Perrotin's avatar
Maxime Perrotin committed
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

import string

# Parser for ASN.1 Value Notation
# Based on the ASN1Scc grammar

BitStringLiteral = ('"' + Word("01") + '"B').setResultsName('BITSTRING')

OctetStringLiteral=('"' + Word(string.hexdigits) + '"H').setResultsName('OCTETSTRING')

# QuotedString's first parameter = quote type..+multiline to support \n  => OK
# Support embedded quotes as per GSER standard (""embedded quoted text"")
StringLiteral = QuotedString('"', escQuote='""', multiline=True,).setResultsName('QUOTEDSTRING')

TRUE = Literal("TRUE").setResultsName('TRUE')
FALSE = Literal("FALSE").setResultsName('FALSE')

NULL = Literal("NULL").setResultsName('NULL')
COMMA = Literal(',').suppress()

PLUS_INFINITY = Literal("PLUS-INFINITY").setResultsName('PLUS-INFINITY')
MINUS_INFINITY = Literal("MINUS-INFINITY").setResultsName('MINUS-INFINITY')

# EMPTY_LIST:
LBRACKET = Literal('{').suppress()
RBRACKET = Literal('}').suppress()

# INTEGER
INT = Combine(Optional(oneOf("+ -")) + (Word(srange("[1-9]"), nums)|Literal('0'))).setResultsName('INTEGER')

# This one is correct:
# a lowercase followed by a-zA-z and -
#LID = Word(string.lowercase, string.letters+string.digits+'-')
# Update MP 21/11/12: made it tolerant to uppercase for the first character
LID = Word(string.letters, string.letters+string.digits+'-')
identifier = LID.setResultsName('IDENTIFIER')

Maxime Perrotin's avatar
Maxime Perrotin committed
73
# Value reference is in practice used to identify enumerated values
Maxime Perrotin's avatar
Maxime Perrotin committed
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
valuereference = LID.setResultsName('VALUE_REF')

# FloatingPointLiteral
DOT = Literal('.')
DOUBLE_DOT = Literal('..')

# Exponent (e.g. e+10)
Exponent = oneOf("e E") + Optional(oneOf("+ -")) + OneOrMore(Word(nums))

# Thefirst (INT + DOUBLE_DOT) is unclear (e.g. "5..").
FloatingPointLiteral = (INT + DOUBLE_DOT
                       | Combine(INT + DOT + Optional(Word(nums)) + Optional(Exponent))
                       | INT).setResultsName('REAL1')

# Numeric value2 (eg. { mantissa 3, base 4, exponent 5 })
MANTISSA = Literal('mantissa').suppress()
BASE = Literal('base').suppress()
EXPONENT = Literal('exponent').suppress()

NUMERIC_VALUE2 = (nestedExpr('{', '}', MANTISSA + INT + COMMA + BASE + INT + COMMA + EXPONENT + INT)).setResultsName('REAL2')

# Forward allows to use recursive constructs
NAMED_VALUE_LIST = Forward()
VALUE_LIST = Forward()
choiceValue = Forward()

# Support for "Any" value (using a star)
AnyValueLiteral = Keyword('*').setResultsName('ANY')

# ASN.1 Value Notation: only missing construct are OID references
# Ambiguity: FloatingPointLiteral contains INT -> INT will never be parsed as REAL
value = (BitStringLiteral
        | OctetStringLiteral
        | TRUE
        | FALSE
        | StringLiteral
        | NULL
        | PLUS_INFINITY
        | MINUS_INFINITY
        | NAMED_VALUE_LIST
        | VALUE_LIST
        | (valuereference ^ choiceValue)
        | (INT ^ FloatingPointLiteral)
        | NUMERIC_VALUE2
        | AnyValueLiteral)

# namedValue is used for SEQUENCE fields
namedValue = identifier + value

# ASN.1 CHOICE
124
choiceValue << (identifier + ':' + value)#.setResultsName('CHOICE')
Maxime Perrotin's avatar
Maxime Perrotin committed
125
126
127
128
129
130
131
132
133
134
135
136

# ASN.1 SEQUENCE
NAMED_VALUE_LIST << LBRACKET + delimitedList(namedValue) + RBRACKET

# ASN.1 SEQUENCE OF
VALUE_LIST << LBRACKET + Optional(delimitedList(value)) + RBRACKET

# Parse actions allow to modify the AST to be compliant with the ASN.1 Editor input
NAMED_VALUE_LIST.setParseAction(lambda s, l, t: reduce(lambda a, b: a.update(b) or a, t, {}))
# below: works only with Python 2.7+
#NAMED_VALUE_LIST.setParseAction(lambda s, l, t: {c:a[c] for a in t for c in a.iterkeys()})
VALUE_LIST.setParseAction(lambda s, l, t: [t.asList()])
137
138
139

def parseChoiceValue(s, l, t):
    ''' Parsing CHOICE '''
140
    choice = t[0]
141
142
143
144
145
146
    return {'Choice': choice, choice: t[2]}

choiceValue.setParseAction(parseChoiceValue)

def parseValueReference(s, l, t):
    ''' Parsing ENUMERATED Id '''
147
    value = t[0]
148
149
150
151
    return {'Enum': value}

valuereference.setParseAction(parseValueReference)

152
namedValue.setParseAction(lambda s, l, t: {t[0]: t[1]})
Maxime Perrotin's avatar
Maxime Perrotin committed
153
154
155
156
157
158
159
160
161
162
163
FloatingPointLiteral.setParseAction(lambda s, l, t: float(t[0]))
INT.setParseAction(lambda s, l, t: int(t[0]))
TRUE.setParseAction(lambda s, l, t: True)
FALSE.setParseAction(lambda s, l, t: False)
AnyValueLiteral.setParseAction(lambda s, l, t: {'Any': t[0]})
OctetStringLiteral.setParseAction(lambda s, l, t: ''.join([chr(int(t[1][i:i+2], 16)) for i in range(0, len(t[1]), 2)]))
# BitString Warning: will only work with series of 8 bits
BitStringLiteral.setParseAction(lambda s, l, t: ''.join([chr(int(t[1][i:i+9], 2)) for i in range(0, len(t[1]), 2)]))

def fromValueNotationToPySide(varName, string):
    ''' Return a variable compatible with the ASN.1 Editor from a GSER string'''
Maxime Perrotin's avatar
Maxime Perrotin committed
164
165
166
167
168
    try:
        return {varName: value.parseString(string, True)[0]}
    except ParseException as err:
        print '[fromValueNotationToPySide] Parsing error:', string
        raise
Maxime Perrotin's avatar
Maxime Perrotin committed
169
170


171
172
def format_gser(gser):
    ''' Reformat a GSER string '''
Maxime Perrotin's avatar
Maxime Perrotin committed
173
174
175
    return ', '.join(u.strip()
        for u in ' '.join(gser.split())
        .split(',')).replace(' :', ':').replace('{ ', '{').replace(' }', '}')
176
177


Maxime Perrotin's avatar
Maxime Perrotin committed
178
179
def toASN1ValueNotation(val):
    ''' Create a GSER reprentation of the Python variable '''
Maxime Perrotin's avatar
Maxime Perrotin committed
180
    # DEPRECATED. No more use of the Python variable
Maxime Perrotin's avatar
Maxime Perrotin committed
181
182
183
    result = ''
    if isinstance(val, dict):
        if 'Choice' in val:
184
            result += val['Choice'].strip() + ':'
Maxime Perrotin's avatar
Maxime Perrotin committed
185
186
            result += toASN1ValueNotation(val[val['Choice']])
        elif 'Enum' in val:
187
            result += unicode(val['Enum']).strip()
Maxime Perrotin's avatar
Maxime Perrotin committed
188
189
190
191
192
193
        else:  # SEQUENCE and SET
            result += ' { '
            needsComa = False
            for seqElem in val:
                if needsComa:
                    result += ', '
194
                result += seqElem.strip() + ' '
Maxime Perrotin's avatar
Maxime Perrotin committed
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
                result += toASN1ValueNotation(val[seqElem])
                needsComa = True
            result += ' }'
    elif isinstance(val, list):  # SEQUENCE OF or SET OF
        result += ' { '
        needsComa = False
        for seqOfElem in val:
            if needsComa:
                result += ', '
            result += toASN1ValueNotation(seqOfElem)
            needsComa = True
        result += ' }'
    elif isinstance(val, bool):
        # boolean are in upper case in ASN.1
        result += str(val).upper()
    elif isinstance(val, basestring):
        # Strings: add quotes, and if string contain non-displayable chars, use repr() to get a visible string
        if all(c in string.printable for c in val):
            result = '"' + val + '"'
        else:
            result = '"'
            for c in val:
                result += '%02x' % ord(c)
            result += '"H'
    else:
        result = str(val)  # INTEGER and REAL
    return result

Maxime Perrotin's avatar
Maxime Perrotin committed
223

224
225
def valueNotationToCTypes(gser, dest, sort, ASN1Mod, ASN1_AST, var=None):
    ''' Parse a GSER value and fill a Native (ctypes) variable with it
Maxime Perrotin's avatar
Maxime Perrotin committed
226
227
        Inputs:
            gser : input GSER string
228
229
            dest : output ctypes instance to be filled
            ASN1Mod : python module containing ctypes DV access
Maxime Perrotin's avatar
Maxime Perrotin committed
230
231
            sort: ASN1 type from ASN1_AST
            ASN1_AST : AST generated by ASN1SCC (python.stg)
Maxime Perrotin's avatar
Maxime Perrotin committed
232
233
234
235
            var : optional already pyside-converted GSER string
        Outputs:
            none - "dest" is modified by this function
    '''
Maxime Perrotin's avatar
Maxime Perrotin committed
236
237
    if var is None:
        var = value.parseString(gser, True)[0]
238

Maxime Perrotin's avatar
Maxime Perrotin committed
239
    def reach(field, orig, idx=True):
240
        ''' Helper: move native pointer to the next field, and optionaly
Maxime Perrotin's avatar
Maxime Perrotin committed
241
242
243
244
245
246
            index (if idx=True)
            Inputs: field is a string with optional index (e.g. "a[0]")
                    orig is the swig pointer
                    idx: set to true if you want the index to be reached
        '''
        split = field.strip(']').split('[')
247
        ptr = getattr(orig, split[0]) if split and split[0] else orig
Maxime Perrotin's avatar
Maxime Perrotin committed
248
249
250
251
252
253
        if len(split) > 1 and idx:
            # SEQOF index
            ptr = ptr[int(split[1])]
    def rec(inp, outp, sort):
        ''' Recursively fill up the value '''
        if sort.kind == 'ReferenceType':
Maxime Perrotin's avatar
Maxime Perrotin committed
254
            sort = ASN1_AST[sort.ReferencedTypeName].type
Maxime Perrotin's avatar
Maxime Perrotin committed
255
256
257
258
259
260
261
262
263
264
265
        if isinstance(inp, list):
            # SEQUENCE OF
            # get the path to the sequence of
            _, params, path = outp.GetState()
            if path:
                path = path.strip('.').split('.')
            for i in range(len(inp)):
                outp.Reset()
                for each in path:
                    reach(each, outp)
                # Follow the ASN.1 type in the AST from ASN1SCC
266
267
                rec(inp[i], outp[i], sort.type)
            if sort.Min != sort.Max:
Maxime Perrotin's avatar
Maxime Perrotin committed
268
269
270
271
272
273
274
                outp.Reset()
                for each in path:
                    reach(each, outp)
                # The ASN1SCC AST only knows if the list has a fixed length
                outp.SetLength(len(inp))
        elif isinstance(inp, (int, float, bool)):
            outp.Set(inp)
275
276
        elif isinstance(inp, str):
            outp.SetFromPyString(inp)
Maxime Perrotin's avatar
Maxime Perrotin committed
277
278
279
        elif isinstance(inp, dict):
            if 'Enum' in inp:
                # Get proper enum id from the ASN1SCC AST
280
                enum_id = sort.EnumValues[inp['Enum'].replace('_', '-')].EnumID
Maxime Perrotin's avatar
Maxime Perrotin committed
281
                #print ASN1Mod.DV.__file__
282
                val = getattr(ASN1Mod.DV, enum_id)
Maxime Perrotin's avatar
Maxime Perrotin committed
283
284
285
                outp.Set(val)
            elif 'Choice' in inp:
                child_name = inp['Choice']
286
                ch_ty = sort.Children[child_name.replace('_', '-')]
287
                enum_val = getattr(ASN1Mod.DV, ch_ty.EnumID)
Maxime Perrotin's avatar
Maxime Perrotin committed
288
                state = outp.GetState()
Maxime Perrotin's avatar
Maxime Perrotin committed
289
                outp.kind.Set(enum_val)
Maxime Perrotin's avatar
Maxime Perrotin committed
290
291
292
                outp.Reset(state)
                reach(child_name.replace('-', '_'), outp)
                rec(inp[child_name], outp, ch_ty.type)
Maxime Perrotin's avatar
Maxime Perrotin committed
293
294
295
296
297
298
299
300
301
302
303
304
305
            else:
                # SEQUENCE
                # get the path to the sequence
                _, params, path = outp.GetState()
                if path:
                    path = path.strip('.').split('.')
                for field, data in inp.viewitems():
                    outp.Reset()
                    for each in path:
                        # Reach the path, including indexes
                        reach(each, outp)
                    # Then get the field itself
                    reach(field.replace('-', '_'), outp)
306
                    field_ty = sort.Children[field.replace('_', '-')]
Maxime Perrotin's avatar
Maxime Perrotin committed
307
308
309
310
311
312
313
                    rec(data, outp, field_ty.type)
                # move back to original path
                outp.Reset()
                if len(path):
                    reach(path[0], outp)
        else:
            # Unsupported type
314
            raise NotImplementedError('vn - type conversion error')
Maxime Perrotin's avatar
Maxime Perrotin committed
315
316
317
    rec(var, dest, sort)


Maxime Perrotin's avatar
Maxime Perrotin committed
318
319
320
321
322
if __name__ == '__main__':
    ''' Test application '''
    import sys
    if len(sys.argv)==2:
        print fromValueNotationToPySide(sys.argv[1])