5 # ASN.1 to Wireshark dissector compiler
11 """ASN.1 to Wireshark dissector compiler"""
14 # Compiler from ASN.1 specification to the Wireshark dissector
16 # Based on ASN.1 to Python compiler from Aaron S. Lav's PyZ3950 package licensed under the X Consortium license
17 # http://www.pobox.com/~asl2/software/PyZ3950/
18 # (ASN.1 to Python compiler functionality is broken but not removed, it could be revived if necessary)
20 # It requires Dave Beazley's PLY parsing package licensed under the LGPL (tested with version 2.3)
21 # http://www.dabeaz.com/ply/
24 # ITU-T Recommendation X.680 (07/2002),
25 # Information technology - Abstract Syntax Notation One (ASN.1): Specification of basic notation
27 # ITU-T Recommendation X.681 (07/2002),
28 # Information technology - Abstract Syntax Notation One (ASN.1): Information object specification
30 # ITU-T Recommendation X.682 (07/2002),
31 # Information technology - Abstract Syntax Notation One (ASN.1): Constraint specification
33 # ITU-T Recommendation X.683 (07/2002),
34 # Information technology - Abstract Syntax Notation One (ASN.1): Parameterization of ASN.1 specifications
36 # ITU-T Recommendation X.880 (07/1994),
37 # Information technology - Remote Operations: Concepts, model and notation
40 from __future__ import nested_scopes
55 # OID name -> number conversion table
61 '0/recommendation' : 0,
90 '0/administration' : 2,
91 '0/network-operator' : 3,
92 '0/identified-organization' : 4,
93 '0/r-recommendation' : 5,
97 '1/registration-authority' : 1,
99 '1/identified-organization' : 3,
100 '/joint-iso-itu-t' : 2,
101 '/joint-iso-ccitt' : 2,
102 '2/presentation' : 0,
104 '2/association-control' : 2,
105 '2/reliable-transfer' : 3,
106 '2/remote-operations' : 4,
114 '2/osi-management' : 9,
115 '2/transaction-processing' : 10,
117 '2/distinguished-object-reference' : 11,
118 '2/reference-data-transfe' : 12,
119 '2/network-layer' : 13,
120 '2/network-layer-management' : 13,
121 '2/transport-layer' : 14,
122 '2/transport-layer-management' : 14,
123 '2/datalink-layer' : 15,
124 '2/datalink-layer-managemen' : 15,
125 '2/datalink-layer-management-information' : 15,
127 '2/registration-procedures' : 17,
128 '2/registration-procedure' : 17,
129 '2/physical-layer' : 18,
130 '2/physical-layer-management' : 18,
133 '2/generic-upper-layers-security' : 20,
135 '2/transport-layer-security-protocol' : 21,
136 '2/network-layer-security-protocol' : 22,
137 '2/international-organizations' : 23,
138 '2/internationalRA' : 23,
146 return id.replace('-', '_').replace('.', '_').replace('&', '_')
153 class LexError(Exception):
154 def __init__(self, tok, filename=None):
156 self.filename = filename
157 self.msg = "Unexpected character %r" % (self.tok.value[0])
158 Exception.__init__(self, self.msg)
160 return "%s:%d: %s" % (self.filename, self.tok.lineno, self.msg)
164 class ParseError(Exception):
165 def __init__(self, tok, filename=None):
167 self.filename = filename
168 self.msg = "Unexpected token %s(%r)" % (self.tok.type, self.tok.value)
169 Exception.__init__(self, self.msg)
171 return "%s:%d: %s" % (self.filename, self.tok.lineno, self.msg)
176 ('braceignore','exclusive'),
180 ('left', 'UNION', 'BAR'),
181 ('left', 'INTERSECTION', 'CIRCUMFLEX'),
183 # 11 ASN.1 lexical items
186 r'::=' : 'ASSIGNMENT', # 11.16 Assignment lexical item
187 r'\.\.' : 'RANGE', # 11.17 Range separator
188 r'\.\.\.' : 'ELLIPSIS', # 11.18 Ellipsis
189 #r'\[\[' : 'LVERBRACK', # 11.19 Left version brackets
190 #r'\]\]' : 'RVERBRACK', # 11.20 Right version brackets
191 # 11.26 Single character lexical items
206 #r"'" : 'APOSTROPHE',
209 r'\!' : 'EXCLAMATION',
210 r'\^' : 'CIRCUMFLEX',
215 # 11.27 Reserved words
217 # all keys in reserved_words must start w/ upper case
220 'ABSTRACT-SYNTAX' : 'ABSTRACT_SYNTAX',
222 'APPLICATION' : 'APPLICATION',
223 'AUTOMATIC' : 'AUTOMATIC',
226 'BOOLEAN' : 'BOOLEAN',
228 'CHARACTER' : 'CHARACTER',
231 'COMPONENT' : 'COMPONENT',
232 'COMPONENTS' : 'COMPONENTS',
233 'CONSTRAINED' : 'CONSTRAINED',
234 'CONTAINING' : 'CONTAINING',
235 'DEFAULT' : 'DEFAULT',
236 'DEFINITIONS' : 'DEFINITIONS',
237 'EMBEDDED' : 'EMBEDDED',
238 # 'ENCODED' : 'ENCODED',
240 'ENUMERATED' : 'ENUMERATED',
241 # 'EXCEPT' : 'EXCEPT',
242 'EXPLICIT' : 'EXPLICIT',
243 'EXPORTS' : 'EXPORTS',
244 # 'EXTENSIBILITY' : 'EXTENSIBILITY',
245 'EXTERNAL' : 'EXTERNAL',
248 'GeneralizedTime' : 'GeneralizedTime',
249 'IDENTIFIER' : 'IDENTIFIER',
250 'IMPLICIT' : 'IMPLICIT',
251 # 'IMPLIED' : 'IMPLIED',
252 'IMPORTS' : 'IMPORTS',
253 'INCLUDES' : 'INCLUDES',
254 'INSTANCE' : 'INSTANCE',
255 'INTEGER' : 'INTEGER',
256 'INTERSECTION' : 'INTERSECTION',
259 'MINUS-INFINITY' : 'MINUS_INFINITY',
262 'ObjectDescriptor' : 'ObjectDescriptor',
265 'OPTIONAL' : 'OPTIONAL',
266 'PATTERN' : 'PATTERN',
268 'PLUS-INFINITY' : 'PLUS_INFINITY',
269 'PRESENT' : 'PRESENT',
270 'PRIVATE' : 'PRIVATE',
272 # 'RELATIVE-OID' : 'RELATIVE-OID',
273 'SEQUENCE' : 'SEQUENCE',
280 'TYPE-IDENTIFIER' : 'TYPE_IDENTIFIER',
283 'UNIVERSAL' : 'UNIVERSAL',
284 'UTCTime' : 'UTCTime',
286 # obsolete but still used
290 for k in static_tokens.keys():
291 if static_tokens [k] == None:
292 static_tokens [k] = k
294 StringTypes = ['Numeric', 'Printable', 'IA5', 'BMP', 'Universal', 'UTF8',
295 'Teletex', 'T61', 'Videotex', 'Graphic', 'ISO646', 'Visible',
298 for s in StringTypes:
299 reserved_words[s + 'String'] = s + 'String'
301 tokens = static_tokens.values() \
302 + reserved_words.values() \
303 + ['BSTRING', 'HSTRING', 'QSTRING',
304 'UCASE_IDENT', 'LCASE_IDENT', 'LCASE_IDENT_ASSIGNED', 'CLASS_IDENT',
305 'REAL_NUMBER', 'NUMBER', 'PYQUOTE']
308 cur_mod = __import__ (__name__) # XXX blech!
310 for (k, v) in static_tokens.items ():
311 cur_mod.__dict__['t_' + v] = k
313 # 11.10 Binary strings
318 # 11.12 Hexadecimal strings
327 def t_UCASE_IDENT (t):
328 r"[A-Z](-[a-zA-Z0-9]|[a-zA-Z0-9])*" # can't end w/ '-'
329 if (is_class_ident(t.value)): t.type = 'CLASS_IDENT'
330 if (is_class_syntax(t.value)): t.type = t.value
331 t.type = reserved_words.get(t.value, t.type)
334 lcase_ident_assigned = {}
335 def t_LCASE_IDENT (t):
336 r"[a-z](-[a-zA-Z0-9]|[a-zA-Z0-9])*" # can't end w/ '-'
337 if (not in_oid and lcase_ident_assigned.has_key(t.value)): t.type = 'LCASE_IDENT_ASSIGNED'
341 def t_REAL_NUMBER (t):
342 r"[0-9]+\.[0-9]*(?!\.)"
351 pyquote_str = 'PYQUOTE'
353 r"--(-[^\-\n]|[^\-\n])*(--|\n|-\n|$|-$)"
354 if (t.value.find("\n") >= 0) : t.lexer.lineno += 1
355 if t.value[2:2+len (pyquote_str)] == pyquote_str:
356 t.value = t.value[2+len(pyquote_str):]
357 t.value = t.value.lstrip ()
366 t.lexer.lineno += t.value.count("\n")
370 raise LexError(t, input_file)
372 # state 'braceignore'
374 def t_braceignore_lbrace(t):
378 def t_braceignore_rbrace(t):
381 # If closing brace, return token
382 if t.lexer.level == 0:
386 def t_braceignore_QSTRING (t):
388 t.lexer.lineno += t.value.count("\n")
390 def t_braceignore_COMMENT(t):
391 r"--(-[^\-\n]|[^\-\n])*(--|\n|-\n|$|-$)"
392 if (t.value.find("\n") >= 0) : t.lexer.lineno += 1
394 def t_braceignore_nonspace(t):
395 r'[^\s\{\}\"-]+|-(?!-)'
397 t_braceignore_ignore = " \t\r"
399 def t_braceignore_NEWLINE(t):
401 t.lexer.lineno += t.value.count("\n")
403 def t_braceignore_error(t):
407 def __init__ (self, defined_dict, indent = 0):
408 self.tags_def = 'EXPLICIT' # default = explicit
410 self.assignments = {}
411 self.dependencies = {}
413 self.defined_dict = defined_dict
416 return " " * (4 * self.indent_lev)
421 assert (self.indent_lev >= 0)
422 def register_assignment (self, ident, val, dependencies):
423 if self.assignments.has_key (ident):
424 raise "Duplicate assignment for " + ident
425 if self.defined_dict.has_key (ident):
426 raise "cross-module duplicates for " + ident
427 self.defined_dict [ident] = 1
428 self.assignments[ident] = val
429 self.dependencies [ident] = dependencies
431 # return "#%s depends on %s" % (ident, str (dependencies))
432 def register_pyquote (self, val):
433 self.pyquotes.append (val)
435 def output_assignments (self):
438 assign_keys = self.assignments.keys()
439 to_output_count = len (assign_keys)
442 for (ident, val) in self.assignments.iteritems ():
443 if already_output.has_key (ident):
446 for d in self.dependencies [ident]:
447 if (not already_output.has_key (d) and
451 text_list.append ("%s=%s" % (ident,
452 self.assignments [ident]))
453 already_output [ident] = 1
456 assert (to_output_count >= 0)
458 if to_output_count == 0:
460 # OK, we detected a cycle
462 for ident in self.assignments.iterkeys ():
463 if not already_output.has_key (ident):
464 depend_list = [d for d in self.dependencies[ident] if d in assign_keys]
465 cycle_list.append ("%s(%s)" % (ident, ",".join (depend_list)))
467 text_list.append ("# Cycle XXX " + ",".join (cycle_list))
468 for (ident, val) in self.assignments.iteritems ():
469 if not already_output.has_key (ident):
470 text_list.append ("%s=%s" % (ident, self.assignments [ident]))
473 return "\n".join (text_list)
474 def output_pyquotes (self):
475 return "\n".join (self.pyquotes)
476 def make_new_name (self):
478 return "_compiler_generated_name_%d" % (self.name_ctr,)
480 #--- Flags for EXPORT, USER_DEFINED, NO_EMIT, MAKE_ENUM -------------------------------
492 #--- common dependency computation ---
493 # Input : list of items
494 # dictionary with lists of dependency
497 # Output : list of two outputs:
498 # [0] list of items in dependency
499 # [1] list of cycle dependency cycles
500 def dependency_compute(items, dependency, map_fn = lambda t: t, ignore_fn = lambda t: False):
503 x = {} # already emitted
504 #print '# Dependency computation'
506 if x.has_key(map_fn(t)):
507 #print 'Continue: %s : %s' % (t, (map_fn(t))
510 stackx = {t : dependency.get(t, [])[:]}
511 #print 'Push: %s : %s' % (t, str(stackx[t]))
513 if stackx[stack[-1]]: # has dependencies
514 d = stackx[stack[-1]].pop(0)
515 if x.has_key(map_fn(d)) or ignore_fn(d):
517 if stackx.has_key(d): # cyclic dependency
520 c = [d] + c[0:c.index(d)+1]
523 #print 'Cyclic: %s ' % (' -> '.join(c))
526 stackx[d] = dependency.get(d, [])[:]
527 #print 'Push: %s : %s' % (d, str(stackx[d]))
529 #print 'Pop: %s' % (stack[-1])
530 del stackx[stack[-1]]
531 e = map_fn(stack.pop())
534 #print 'Add: %s' % (e)
537 return (item_ord, item_cyc)
539 #--- EthCtx -------------------------------------------------------------------
541 def __init__(self, conform, output, indent = 0):
542 self.conform = conform
544 self.conform.ectx = self
545 self.output.ectx = self
546 self.encoding = 'per'
549 self.default_oid_variant = ''
550 self.default_opentype_variant = ''
551 self.default_containing_variant = '_pdu_new'
552 self.default_embedded_pdv_cb = None
553 self.default_external_type_cb = None
554 self.emitted_pdu = {}
557 self.all_type_attr = {}
561 def encp(self): # encoding protocol
566 def Per(self): return self.encoding == 'per'
567 def Ber(self): return self.encoding == 'ber'
568 def NewBer(self): return self.new_ber
569 def Aligned(self): return self.aligned
570 def Unaligned(self): return not self.aligned
571 def Fld(self, tnm='*'): return self.fld_opt.get('*', False) or self.fld_opt.get(tnm, False) or (self.Ber() and not self.NewBer())
572 def Tag(self): return self.tag_opt # or self.Ber() - temporary comment out (experimental feature)
573 def NAPI(self): return False # disable planned features
575 def Module(self): # current module name
576 return self.modules[-1][0]
579 return self.group_by_prot or (self.conform.last_group > 0)
582 if (self.dbgopt.find(d) >= 0):
587 def value_max(self, a, b):
588 if (a == 'MAX') or (b == 'MAX'): return 'MAX';
589 if a == 'MIN': return b;
590 if b == 'MIN': return a;
592 if (int(a) > int(b)):
596 except (ValueError, TypeError):
598 return "MAX((%s),(%s))" % (a, b)
600 def value_min(self, a, b):
601 if (a == 'MIN') or (b == 'MIN'): return 'MIN';
602 if a == 'MAX': return b;
603 if b == 'MAX': return a;
605 if (int(a) < int(b)):
609 except (ValueError, TypeError):
611 return "MIN((%s),(%s))" % (a, b)
613 def value_get_eth(self, val):
614 if isinstance(val, Value):
615 return val.to_str(self)
617 if self.value.has_key(val):
618 ethname = self.value[val]['ethname']
621 def value_get_val(self, nm):
623 if self.value.has_key(nm):
624 if self.value[nm]['import']:
625 v = self.get_val_from_all(nm, self.value[nm]['import'])
627 msg = 'Need value of imported value identifier %s from %s (%s)' % (nm, self.value[nm]['import'], self.value[nm]['proto'])
628 warnings.warn_explicit(msg, UserWarning, '', '')
632 val = self.value[nm]['value']
633 if isinstance (val, Value):
634 val = val.to_str(self)
636 msg = 'Need value of unknown value identifier %s' % (nm)
637 warnings.warn_explicit(msg, UserWarning, '', '')
640 def eth_get_type_attr(self, type):
642 while (not self.type[type]['import']
643 and self.type[type]['val'].type == 'Type_Ref'):
644 type = self.type[type]['val'].val
649 if (self.type[t]['import']):
650 attr.update(self.type[t]['attr'])
651 attr.update(self.eth_get_type_attr_from_all(t, self.type[t]['import']))
652 elif (self.type[t]['val'].type == 'SelectionType'):
653 val = self.type[t]['val']
654 (ftype, display) = val.eth_ftype(self)
655 attr.update({ 'TYPE' : ftype, 'DISPLAY' : display,
656 'STRINGS' : val.eth_strings(), 'BITMASK' : '0' });
658 attr.update(self.type[t]['attr'])
659 attr.update(self.eth_type[self.type[t]['ethname']]['attr'])
662 def eth_get_type_attr_from_all(self, type, module):
664 if self.all_type_attr.has_key(module) and self.all_type_attr[module].has_key(type):
665 attr = self.all_type_attr[module][type]
668 def get_ttag_from_all(self, type, module):
670 if self.all_tags.has_key(module) and self.all_tags[module].has_key(type):
671 ttag = self.all_tags[module][type]
674 def get_val_from_all(self, nm, module):
676 if self.all_vals.has_key(module) and self.all_vals[module].has_key(nm):
677 val = self.all_vals[module][nm]
680 def get_obj_repr(self, ident, restr):
681 def set_type_fn(cls, field, fnfield):
682 obj[fnfield + '_fn'] = 'NULL'
683 obj[fnfield + '_pdu'] = 'NULL'
684 if val.has_key(field) and isinstance(val[field], Type_Ref):
685 p = val[field].eth_type_default_pars(self, '')
686 obj[fnfield + '_fn'] = p['TYPE_REF_FN']
687 obj[fnfield + '_fn'] = obj[fnfield + '_fn'] % p # one iteration
688 if (self.conform.check_item('PDU', cls + '.' + field)):
689 obj[fnfield + '_pdu'] = 'dissect_' + self.field[val[field].val]['ethname']
691 # end of get_type_fn()
692 obj = { '_name' : ident, '_ident' : asn2c(ident)}
693 obj['_class'] = self.oassign[ident].cls
694 val = self.oassign[ident].val
707 if not val.has_key(fld):
710 if isinstance(val[f], Node):
711 obj[f] = val[f].fld_obj_repr(self)
714 if (obj['_class'] == 'TYPE-IDENTIFIER') or (obj['_class'] == 'ABSTRACT-SYNTAX'):
715 set_type_fn(obj['_class'], '&Type', '_type')
716 if (obj['_class'] == 'OPERATION'):
717 set_type_fn(obj['_class'], '&ArgumentType', '_argument')
718 set_type_fn(obj['_class'], '&ResultType', '_result')
719 if (obj['_class'] == 'ERROR'):
720 set_type_fn(obj['_class'], '&ParameterType', '_parameter')
723 #--- eth_reg_module -----------------------------------------------------------
724 def eth_reg_module(self, module):
725 #print "eth_reg_module(module='%s')" % (module)
726 name = module.get_name()
727 self.modules.append([name, module.get_proto(self)])
728 if self.module.has_key(name):
729 raise "Duplicate module for " + name
730 self.module[name] = []
731 self.module_ord.append(name)
733 #--- eth_module_dep_add ------------------------------------------------------------
734 def eth_module_dep_add(self, module, dep):
735 self.module[module].append(dep)
737 #--- eth_exports ------------------------------------------------------------
738 def eth_exports(self, exports):
739 self.exports_all = False
740 if ((len(exports) == 1) and (exports[0] == 'ALL')):
741 self.exports_all = True
744 if isinstance(e, Type_Ref):
745 self.exports.append(e.val)
746 elif isinstance(e, Class_Ref):
747 self.cexports.append(e.val)
749 self.vexports.append(e)
751 #--- eth_reg_assign ---------------------------------------------------------
752 def eth_reg_assign(self, ident, val, virt=False):
753 #print "eth_reg_assign(ident='%s')" % (ident)
754 if self.assign.has_key(ident):
755 raise "Duplicate assignment for " + ident
756 self.assign[ident] = { 'val' : val , 'virt' : virt }
757 self.assign_ord.append(ident)
758 if (self.exports_all):
759 self.exports.append(ident)
761 #--- eth_reg_vassign --------------------------------------------------------
762 def eth_reg_vassign(self, vassign):
763 ident = vassign.ident
764 #print "eth_reg_vassign(ident='%s')" % (ident)
765 if self.vassign.has_key(ident):
766 raise "Duplicate value assignment for " + ident
767 self.vassign[ident] = vassign
768 self.vassign_ord.append(ident)
769 if (self.exports_all):
770 self.vexports.append(ident)
772 #--- eth_reg_oassign --------------------------------------------------------
773 def eth_reg_oassign(self, oassign):
774 ident = oassign.ident
775 #print "eth_reg_oassign(ident='%s')" % (ident)
776 if self.oassign.has_key(ident):
777 if self.oassign[ident] == oassign:
778 return # OK - already defined
780 raise "Duplicate information object assignment for " + ident
781 self.oassign[ident] = oassign
782 self.oassign_ord.append(ident)
783 self.oassign_cls.setdefault(oassign.cls, []).append(ident)
785 #--- eth_import_type --------------------------------------------------------
786 def eth_import_type(self, ident, mod, proto):
787 #print "eth_import_type(ident='%s', mod='%s', prot='%s')" % (ident, mod, proto)
788 if self.type.has_key(ident):
789 #print "already defined import=%s, module=%s" % (str(self.type[ident]['import']), self.type[ident]['module'])
790 if not self.type[ident]['import'] and (self.type[ident]['module'] == mod) :
791 return # OK - already defined
792 elif self.type[ident]['import'] and (self.type[ident]['import'] == mod) :
793 return # OK - already imported
795 raise "Duplicate type for " + ident
796 self.type[ident] = {'import' : mod, 'proto' : proto,
798 self.type[ident]['attr'] = { 'TYPE' : 'FT_NONE', 'DISPLAY' : 'BASE_NONE',
799 'STRINGS' : 'NULL', 'BITMASK' : '0' }
800 self.type[ident]['attr'].update(self.conform.use_item('TYPE_ATTR', ident))
801 self.type_imp.append(ident)
803 #--- dummy_import_type --------------------------------------------------------
804 def dummy_import_type(self, ident):
806 if self.type.has_key(ident):
807 raise "Try to dummy import for existing type :" + ident
808 ethtype = asn2c(ident)
809 self.type[ident] = {'import' : 'xxx', 'proto' : 'xxx',
810 'ethname' : ethtype }
811 self.type[ident]['attr'] = { 'TYPE' : 'FT_NONE', 'DISPLAY' : 'BASE_NONE',
812 'STRINGS' : 'NULL', 'BITMASK' : '0' }
813 self.eth_type[ethtype] = { 'import' : 'xxx', 'proto' : 'xxx' , 'attr' : {}, 'create_field' : False, 'ref' : []}
814 print "Dummy imported: %s (%s)" % (ident, ethtype)
817 #--- eth_import_class --------------------------------------------------------
818 def eth_import_class(self, ident, mod, proto):
819 #print "eth_import_class(ident='%s', mod='%s', prot='%s')" % (ident, mod, proto)
820 if self.objectclass.has_key(ident):
821 #print "already defined import=%s, module=%s" % (str(self.objectclass[ident]['import']), self.objectclass[ident]['module'])
822 if not self.objectclass[ident]['import'] and (self.objectclass[ident]['module'] == mod) :
823 return # OK - already defined
824 elif self.objectclass[ident]['import'] and (self.objectclass[ident]['import'] == mod) :
825 return # OK - already imported
827 raise "Duplicate object class for " + ident
828 self.objectclass[ident] = {'import' : mod, 'proto' : proto,
830 self.objectclass_imp.append(ident)
832 #--- eth_import_value -------------------------------------------------------
833 def eth_import_value(self, ident, mod, proto):
834 #print "eth_import_value(ident='%s', mod='%s', prot='%s')" % (ident, mod, prot)
835 if self.value.has_key(ident):
836 #print "already defined import=%s, module=%s" % (str(self.value[ident]['import']), self.value[ident]['module'])
837 if not self.value[ident]['import'] and (self.value[ident]['module'] == mod) :
838 return # OK - already defined
839 elif self.value[ident]['import'] and (self.value[ident]['import'] == mod) :
840 return # OK - already imported
842 raise "Duplicate value for " + ident
843 self.value[ident] = {'import' : mod, 'proto' : proto,
845 self.value_imp.append(ident)
847 #--- eth_sel_req ------------------------------------------------------------
848 def eth_sel_req(self, typ, sel):
849 key = typ + '.' + sel
850 if not self.sel_req.has_key(key):
851 self.sel_req[key] = { 'typ' : typ , 'sel' : sel}
852 self.sel_req_ord.append(key)
855 #--- eth_comp_req ------------------------------------------------------------
856 def eth_comp_req(self, type):
857 self.comp_req_ord.append(type)
859 #--- eth_dep_add ------------------------------------------------------------
860 def eth_dep_add(self, type, dep):
861 if not self.type_dep.has_key(type):
862 self.type_dep[type] = []
863 self.type_dep[type].append(dep)
865 #--- eth_reg_type -----------------------------------------------------------
866 def eth_reg_type(self, ident, val):
867 #print "eth_reg_type(ident='%s', type='%s')" % (ident, val.type)
868 if self.type.has_key(ident):
869 if self.type[ident]['import'] and (self.type[ident]['import'] == self.Module()) :
870 # replace imported type
872 self.type_imp.remove(ident)
874 raise "Duplicate type for " + ident
875 self.type[ident] = { 'val' : val, 'import' : None }
876 self.type[ident]['module'] = self.Module()
877 self.type[ident]['proto'] = self.proto
878 if len(ident.split('/')) > 1:
879 self.type[ident]['tname'] = val.eth_tname()
881 self.type[ident]['tname'] = asn2c(ident)
882 self.type[ident]['export'] = self.conform.use_item('EXPORTS', ident)
883 self.type[ident]['enum'] = self.conform.use_item('MAKE_ENUM', ident)
884 self.type[ident]['user_def'] = self.conform.use_item('USER_DEFINED', ident)
885 self.type[ident]['no_emit'] = self.conform.use_item('NO_EMIT', ident)
886 self.type[ident]['tname'] = self.conform.use_item('TYPE_RENAME', ident, val_dflt=self.type[ident]['tname'])
887 self.type[ident]['ethname'] = ''
888 if (val.type == 'Type_Ref') or (val.type == 'SelectionType') :
889 self.type[ident]['attr'] = {}
891 (ftype, display) = val.eth_ftype(self)
892 self.type[ident]['attr'] = { 'TYPE' : ftype, 'DISPLAY' : display,
893 'STRINGS' : val.eth_strings(), 'BITMASK' : '0' }
894 self.type[ident]['attr'].update(self.conform.use_item('TYPE_ATTR', ident))
895 self.type_ord.append(ident)
897 if (self.conform.check_item('PDU', ident)):
898 self.eth_reg_field(ident, ident, impl=val.HasImplicitTag(self), pdu=self.conform.use_item('PDU', ident))
900 #--- eth_reg_objectclass ----------------------------------------------------------
901 def eth_reg_objectclass(self, ident, val):
902 #print "eth_reg_objectclass(ident='%s')" % (ident)
903 if self.objectclass.has_key(ident):
904 if self.objectclass[ident]['import'] and (self.objectclass[ident]['import'] == self.Module()) :
905 # replace imported object class
906 del self.objectclass[ident]
907 self.objectclass_imp.remove(ident)
908 elif isinstance(self.objectclass[ident]['val'], Class_Ref) and \
909 isinstance(val, Class_Ref) and \
910 (self.objectclass[ident]['val'].val == val.val):
911 pass # ignore duplicated CLASS1 ::= CLASS2
913 raise "Duplicate object class for " + ident
914 self.objectclass[ident] = { 'import' : None, 'module' : self.Module(), 'proto' : self.proto }
915 self.objectclass[ident]['val'] = val
916 self.objectclass[ident]['export'] = self.conform.use_item('EXPORTS', ident)
917 self.objectclass_ord.append(ident)
919 #--- eth_reg_value ----------------------------------------------------------
920 def eth_reg_value(self, ident, type, value, ethname=None):
921 #print "eth_reg_value(ident='%s')" % (ident)
922 if self.value.has_key(ident):
923 if self.value[ident]['import'] and (self.value[ident]['import'] == self.Module()) :
924 # replace imported value
925 del self.value[ident]
926 self.value_imp.remove(ident)
928 self.value[ident]['ethname'] = ethname
931 raise "Duplicate value for " + ident
932 self.value[ident] = { 'import' : None, 'module' : self.Module(), 'proto' : self.proto,
933 'type' : type, 'value' : value,
935 self.value[ident]['export'] = self.conform.use_item('EXPORTS', ident)
936 self.value[ident]['ethname'] = ''
937 if (ethname): self.value[ident]['ethname'] = ethname
938 self.value_ord.append(ident)
940 #--- eth_reg_field ----------------------------------------------------------
941 def eth_reg_field(self, ident, type, idx='', parent=None, impl=False, pdu=None):
942 #print "eth_reg_field(ident='%s', type='%s')" % (ident, type)
943 if self.field.has_key(ident):
944 if pdu and (type == self.field[ident]['type']):
945 pass # OK already created PDU
947 raise "Duplicate field for " + ident
948 self.field[ident] = {'type' : type, 'idx' : idx, 'impl' : impl, 'pdu' : pdu,
949 'modified' : '', 'attr' : {} , 'create_field' : False }
950 name = ident.split('/')[-1]
951 if len(ident.split('/')) > 1 and name == '_item': # Sequnce/Set of type
952 self.field[ident]['attr']['NAME'] = '"Item"'
953 self.field[ident]['attr']['ABBREV'] = asn2c(ident.split('/')[-2] + name)
955 self.field[ident]['attr']['NAME'] = '"%s"' % name
956 self.field[ident]['attr']['ABBREV'] = asn2c(name)
957 if self.conform.check_item('FIELD_ATTR', ident):
958 self.field[ident]['modified'] = '#' + str(id(self))
959 self.field[ident]['attr'].update(self.conform.use_item('FIELD_ATTR', ident))
961 self.pdu_ord.append(ident)
963 self.field_ord.append(ident)
965 self.field[ident]['create_field'] = self.Fld(parent)
966 self.eth_dep_add(parent, type)
968 #--- eth_clean --------------------------------------------------------------
970 self.proto = self.proto_opt;
971 #--- ASN.1 tables ----------------
982 self.sel_req_ord = []
983 self.comp_req_ord = []
985 self.vassign_ord = []
989 self.objectclass = {}
990 self.objectclass_ord = []
991 self.objectclass_imp = []
993 self.oassign_ord = []
994 self.oassign_cls = {}
995 #--- Modules ------------
997 self.exports_all = False
1001 #--- types -------------------
1003 self.eth_type_ord = []
1004 self.eth_export_ord = []
1005 self.eth_type_dupl = {}
1007 #--- value dependencies -------------------
1009 #--- values -------------------
1011 self.eth_value_ord = []
1012 #--- fields -------------------------
1014 self.eth_hf_ord = []
1015 self.eth_hfpdu_ord = []
1016 self.eth_hf_dupl = {}
1017 #--- type dependencies -------------------
1018 self.eth_type_ord1 = []
1019 self.eth_dep_cycle = []
1020 self.dep_cycle_eth_type = {}
1021 #--- value dependencies and export -------------------
1022 self.eth_value_ord1 = []
1023 self.eth_vexport_ord = []
1025 #--- eth_prepare ------------------------------------------------------------
1026 def eth_prepare(self):
1027 self.eproto = asn2c(self.proto)
1029 #--- dummy types/fields for PDU registration ---
1031 if (self.conform.check_item('PDU', nm)):
1032 self.eth_reg_type('_dummy/'+nm, NullType())
1033 self.eth_reg_field(nm, '_dummy/'+nm, pdu=self.conform.use_item('PDU', nm))
1035 #--- required PDUs ----------------------------
1036 for t in self.type_ord:
1037 pdu = self.type[t]['val'].eth_need_pdu(self)
1038 if not pdu: continue
1041 pdu['hidden'] = False
1042 pdu['need_decl'] = True
1043 if not self.field.has_key(f):
1044 self.eth_reg_field(f, f, pdu=pdu)
1046 #--- values -> named values -------------------
1048 for v in self.value_ord:
1049 if (self.value[v]['type'].type == 'Type_Ref'):
1050 tnm = self.value[v]['type'].val
1051 if self.type.has_key(tnm) \
1052 and not self.type[tnm]['import'] \
1053 and (self.type[tnm]['val'].type == 'IntegerType'):
1054 self.type[tnm]['val'].add_named_value(v, self.value[v]['value'])
1055 self.value[v]['no_emit'] = True
1056 t_for_update[tnm] = True
1057 for t in t_for_update.keys():
1058 self.type[t]['attr']['STRINGS'] = self.type[t]['val'].eth_strings()
1059 self.type[t]['attr'].update(self.conform.use_item('TYPE_ATTR', t))
1061 #--- required components of ---------------------------
1062 #print "self.comp_req_ord = ", self.comp_req_ord
1063 for t in self.comp_req_ord:
1064 self.type[t]['val'].eth_reg_sub(t, self, components_available=True)
1066 #--- required selection types ---------------------------
1067 #print "self.sel_req_ord = ", self.sel_req_ord
1068 for t in self.sel_req_ord:
1069 tt = self.sel_req[t]['typ']
1070 if not self.type.has_key(tt):
1071 self.dummy_import_type(t)
1072 elif self.type[tt]['import']:
1073 self.eth_import_type(t, self.type[tt]['import'], self.type[tt]['proto'])
1075 self.type[tt]['val'].sel_req(t, self.sel_req[t]['sel'], self)
1077 #--- types -------------------
1078 for t in self.type_imp:
1080 self.eth_type[nm] = { 'import' : self.type[t]['import'],
1081 'proto' : asn2c(self.type[t]['proto']),
1082 'attr' : {}, 'create_field' : False, 'ref' : []}
1083 self.eth_type[nm]['attr'].update(self.conform.use_item('ETYPE_ATTR', nm))
1084 self.type[t]['ethname'] = nm
1085 for t in self.type_ord:
1086 nm = self.type[t]['tname']
1087 if ((nm.find('#') >= 0) or
1088 ((len(t.split('/'))>1) and
1089 (self.conform.get_fn_presence(t) or self.conform.check_item('FN_PARS', t)) and
1090 not self.conform.check_item('TYPE_RENAME', t))):
1091 if len(t.split('/')) == 2 and t.split('/')[1] == '_item': # Sequnce of type at the 1st level
1092 nm = t.split('/')[0] + t.split('/')[1]
1093 elif t.split('/')[-1] == '_item': # Sequnce/Set of type at next levels
1094 nm = 'T_' + self.conform.use_item('FIELD_RENAME', '/'.join(t.split('/')[0:-1]), val_dflt=t.split('/')[-2]) + t.split('/')[-1]
1095 elif t.split('/')[-1] == '_untag': # Untagged type
1096 nm = self.type['/'.join(t.split('/')[0:-1])]['ethname'] + '_U'
1098 nm = 'T_' + self.conform.use_item('FIELD_RENAME', t, val_dflt=t.split('/')[-1])
1100 if self.eth_type.has_key(nm):
1101 if self.eth_type_dupl.has_key(nm):
1102 self.eth_type_dupl[nm].append(t)
1104 self.eth_type_dupl[nm] = [self.eth_type[nm]['ref'][0], t]
1105 nm += '_%02d' % (len(self.eth_type_dupl[nm])-1)
1106 if self.eth_type.has_key(nm):
1107 self.eth_type[nm]['ref'].append(t)
1109 self.eth_type_ord.append(nm)
1110 self.eth_type[nm] = { 'import' : None, 'proto' : self.eproto, 'export' : 0, 'enum' : 0,
1111 'user_def' : EF_TYPE|EF_VALS, 'no_emit' : EF_TYPE|EF_VALS,
1112 'val' : self.type[t]['val'],
1114 'create_field' : False, 'ref' : [t]}
1115 self.type[t]['ethname'] = nm
1116 if (not self.eth_type[nm]['export'] and self.type[t]['export']): # new export
1117 self.eth_export_ord.append(nm)
1118 self.eth_type[nm]['export'] |= self.type[t]['export']
1119 self.eth_type[nm]['enum'] |= self.type[t]['enum']
1120 self.eth_type[nm]['user_def'] &= self.type[t]['user_def']
1121 self.eth_type[nm]['no_emit'] &= self.type[t]['no_emit']
1122 if self.type[t]['attr'].get('STRINGS') == '$$':
1123 self.eth_type[nm]['attr']['STRINGS'] = 'VALS(%s)' % (self.eth_vals_nm(nm))
1124 self.eth_type[nm]['attr'].update(self.conform.use_item('ETYPE_ATTR', nm))
1125 for t in self.eth_type_ord:
1126 bits = self.eth_type[t]['val'].eth_named_bits()
1128 for (val, id) in bits:
1129 self.named_bit.append({'name' : id, 'val' : val,
1130 'ethname' : 'hf_%s_%s_%s' % (self.eproto, t, asn2c(id)),
1131 'ftype' : 'FT_BOOLEAN', 'display' : '8',
1133 'bitmask' : '0x'+('80','40','20','10','08','04','02','01')[val%8]})
1134 if self.eth_type[t]['val'].eth_need_tree():
1135 self.eth_type[t]['tree'] = "ett_%s_%s" % (self.eth_type[t]['proto'], t)
1137 self.eth_type[t]['tree'] = None
1139 #--- register values from enums ------------
1140 for t in self.eth_type_ord:
1141 if (self.eth_type[t]['val'].eth_has_enum(t, self)):
1142 self.eth_type[t]['val'].reg_enum_vals(t, self)
1144 #--- value dependencies -------------------
1145 for v in self.value_ord:
1146 if isinstance (self.value[v]['value'], Value):
1147 dep = self.value[v]['value'].get_dep()
1149 dep = self.value[v]['value']
1150 if dep and self.value.has_key(dep):
1151 self.value_dep.setdefault(v, []).append(dep)
1153 #--- exports all necessary values
1154 for v in self.value_ord:
1155 if not self.value[v]['export']: continue
1156 deparr = self.value_dep.get(v, [])
1159 if not self.value[d]['import']:
1160 if not self.value[d]['export']:
1161 self.value[d]['export'] = EF_TYPE
1162 deparr.extend(self.value_dep.get(d, []))
1164 #--- values -------------------
1165 for v in self.value_imp:
1167 self.eth_value[nm] = { 'import' : self.value[v]['import'],
1168 'proto' : asn2c(self.value[v]['proto']),
1170 self.value[v]['ethname'] = nm
1171 for v in self.value_ord:
1172 if (self.value[v]['ethname']):
1174 if (self.value[v]['no_emit']):
1177 self.eth_value[nm] = { 'import' : None,
1178 'proto' : asn2c(self.value[v]['proto']),
1179 'export' : self.value[v]['export'], 'ref' : [v] }
1180 self.eth_value[nm]['value'] = self.value[v]['value']
1181 self.eth_value_ord.append(nm)
1182 self.value[v]['ethname'] = nm
1184 #--- fields -------------------------
1185 for f in (self.pdu_ord + self.field_ord):
1186 if len(f.split('/')) > 1 and f.split('/')[-1] == '_item': # Sequnce/Set of type
1187 nm = self.conform.use_item('FIELD_RENAME', '/'.join(f.split('/')[0:-1]), val_dflt=f.split('/')[-2]) + f.split('/')[-1]
1189 nm = f.split('/')[-1]
1190 nm = self.conform.use_item('FIELD_RENAME', f, val_dflt=nm)
1192 if (self.field[f]['pdu']):
1194 if (not self.merge_modules):
1195 nm = self.eproto + '_' + nm
1196 t = self.field[f]['type']
1197 if self.type.has_key(t):
1198 ethtype = self.type[t]['ethname']
1199 else: # undefined type
1200 ethtype = self.dummy_import_type(t)
1201 ethtypemod = ethtype + self.field[f]['modified']
1202 if self.eth_hf.has_key(nm):
1203 if self.eth_hf_dupl.has_key(nm):
1204 if self.eth_hf_dupl[nm].has_key(ethtypemod):
1205 nm = self.eth_hf_dupl[nm][ethtypemod]
1206 self.eth_hf[nm]['create_field'] = self.eth_hf[nm]['create_field'] or self.field[f]['create_field']
1207 self.eth_hf[nm]['ref'].append(f)
1208 self.field[f]['ethname'] = nm
1209 self.eth_type[ethtype]['create_field'] = self.eth_type[ethtype]['create_field'] or self.eth_hf[nm]['create_field']
1212 nmx = nm + ('_%02d' % (len(self.eth_hf_dupl[nm])))
1213 self.eth_hf_dupl[nm][ethtype] = nmx
1216 if (self.eth_hf[nm]['ethtype']+self.eth_hf[nm]['modified']) == ethtypemod:
1217 self.eth_hf[nm]['create_field'] = self.eth_hf[nm]['create_field'] or self.field[f]['create_field']
1218 self.eth_hf[nm]['ref'].append(f)
1219 self.field[f]['ethname'] = nm
1220 self.eth_type[ethtype]['create_field'] = self.eth_type[ethtype]['create_field'] or self.eth_hf[nm]['create_field']
1224 self.eth_hf_dupl[nm] = {self.eth_hf[nm]['ethtype']+self.eth_hf[nm]['modified'] : nm, \
1227 if (self.field[f]['pdu']):
1228 self.eth_hfpdu_ord.append(nm)
1230 self.eth_hf_ord.append(nm)
1231 fullname = 'hf_%s_%s' % (self.eproto, nm)
1232 attr = self.eth_get_type_attr(self.field[f]['type']).copy()
1233 attr.update(self.field[f]['attr'])
1234 if (self.NAPI() and attr.has_key('NAME')):
1235 attr['NAME'] += self.field[f]['idx']
1236 attr.update(self.conform.use_item('EFIELD_ATTR', nm))
1237 self.eth_hf[nm] = {'fullname' : fullname, 'pdu' : self.field[f]['pdu'],
1238 'ethtype' : ethtype, 'modified' : self.field[f]['modified'],
1239 'attr' : attr.copy(),
1240 'create_field' : self.field[f]['create_field'],
1242 self.field[f]['ethname'] = nm
1243 self.eth_type[ethtype]['create_field'] = self.eth_type[ethtype]['create_field'] or self.eth_hf[nm]['create_field']
1244 #--- type dependencies -------------------
1245 (self.eth_type_ord1, self.eth_dep_cycle) = dependency_compute(self.type_ord, self.type_dep, map_fn = lambda t: self.type[t]['ethname'], ignore_fn = lambda t: self.type[t]['import'])
1247 while i < len(self.eth_dep_cycle):
1248 t = self.type[self.eth_dep_cycle[i][0]]['ethname']
1249 self.dep_cycle_eth_type.setdefault(t, []).append(i)
1252 #--- value dependencies and export -------------------
1253 for v in self.eth_value_ord:
1254 if self.eth_value[v]['export']:
1255 self.eth_vexport_ord.append(v)
1257 self.eth_value_ord1.append(v)
1259 #--- export tags, values, ... ---
1260 for t in self.exports:
1261 if not self.type.has_key(t):
1263 if self.type[t]['import']:
1265 m = self.type[t]['module']
1267 if not self.all_tags.has_key(m):
1268 self.all_tags[m] = {}
1269 self.all_tags[m][t] = self.type[t]['val'].GetTTag(self)
1270 if not self.all_type_attr.has_key(m):
1271 self.all_type_attr[m] = {}
1272 self.all_type_attr[m][t] = self.eth_get_type_attr(t).copy()
1273 for v in self.vexports:
1274 if not self.value.has_key(v):
1276 if self.value[v]['import']:
1278 m = self.value[v]['module']
1279 if not self.all_vals.has_key(m):
1280 self.all_vals[m] = {}
1281 vv = self.value[v]['value']
1282 if isinstance (vv, Value):
1283 vv = vv.to_str(self)
1284 self.all_vals[m][v] = vv
1286 #--- eth_vals_nm ------------------------------------------------------------
1287 def eth_vals_nm(self, tname):
1289 if (not self.eth_type[tname]['export'] & EF_NO_PROT):
1290 out += "%s_" % (self.eproto)
1291 out += "%s_vals" % (tname)
1294 #--- eth_vals ---------------------------------------------------------------
1295 def eth_vals(self, tname, vals):
1297 has_enum = self.eth_type[tname]['enum'] & EF_ENUM
1298 if (not self.eth_type[tname]['export'] & EF_VALS):
1300 if (self.eth_type[tname]['export'] & EF_VALS) and (self.eth_type[tname]['export'] & EF_TABLE):
1302 out += "const value_string %s[] = {\n" % (self.eth_vals_nm(tname))
1303 for (val, id) in vals:
1305 vval = self.eth_enum_item(tname, id)
1308 out += ' { %3s, "%s" },\n' % (vval, id)
1309 out += " { 0, NULL }\n};\n"
1312 #--- eth_enum_prefix ------------------------------------------------------------
1313 def eth_enum_prefix(self, tname, type=False):
1315 if (self.eth_type[tname]['export'] & EF_ENUM):
1316 no_prot = self.eth_type[tname]['export'] & EF_NO_PROT
1318 no_prot = self.eth_type[tname]['enum'] & EF_NO_PROT
1321 if ((not self.eth_type[tname]['enum'] & EF_NO_TYPE) or type):
1322 if (out): out += '_'
1324 if (self.eth_type[tname]['enum'] & EF_UCASE):
1326 if (out): out += '_'
1329 #--- eth_enum_nm ------------------------------------------------------------
1330 def eth_enum_nm(self, tname):
1331 out = self.eth_enum_prefix(tname, type=True)
1335 #--- eth_enum_item ---------------------------------------------------------------
1336 def eth_enum_item(self, tname, ident):
1337 out = self.eth_enum_prefix(tname)
1339 if (self.eth_type[tname]['enum'] & EF_UCASE):
1343 #--- eth_enum ---------------------------------------------------------------
1344 def eth_enum(self, tname, vals):
1346 if (self.eth_type[tname]['enum'] & EF_DEFINE):
1347 out += "/* enumerated values for %s */\n" % (tname)
1348 for (val, id) in vals:
1349 out += '#define %-12s %3s\n' % (self.eth_enum_item(tname, id), val)
1351 out += "typedef enum _%s {\n" % (self.eth_enum_nm(tname))
1353 for (val, id) in vals:
1354 if (first_line == 1):
1358 out += ' %-12s = %3s' % (self.eth_enum_item(tname, id), val)
1359 out += "\n} %s;\n" % (self.eth_enum_nm(tname))
1362 #--- eth_bits ---------------------------------------------------------------
1363 def eth_bits(self, tname, bits):
1365 out += "static const "
1366 out += "asn_namedbit %(TABLE)s[] = {\n"
1367 for (val, id) in bits:
1368 out += ' { %2d, &hf_%s_%s_%s, -1, -1, "%s", NULL },\n' % (val, self.eproto, tname, asn2c(id), id)
1369 out += " { 0, NULL, 0, 0, NULL, NULL }\n};\n"
1372 #--- eth_type_fn_h ----------------------------------------------------------
1373 def eth_type_fn_h(self, tname):
1375 if (not self.eth_type[tname]['export'] & EF_TYPE):
1379 out += "dissect_%s_%s(gboolean implicit_tag _U_, tvbuff_t *tvb _U_, int offset _U_, asn1_ctx_t *actx _U_, proto_tree *tree _U_, int hf_index _U_)" % (self.eth_type[tname]['proto'], tname)
1381 out += "dissect_%s_%s(tvbuff_t *tvb _U_, int offset _U_, asn1_ctx_t *actx _U_, proto_tree *tree _U_, int hf_index _U_)" % (self.eth_type[tname]['proto'], tname)
1385 #--- eth_fn_call ------------------------------------------------------------
1386 def eth_fn_call(self, fname, ret=None, indent=2, par=None):
1389 if (ret == 'return'):
1395 for i in range(len(par)):
1396 if (i>0): out += ind * ' '
1397 out += ', '.join(par[i])
1398 if (i<(len(par)-1)): out += ',\n'
1402 #--- eth_type_fn_hdr --------------------------------------------------------
1403 def eth_type_fn_hdr(self, tname):
1405 if (not self.eth_type[tname]['export'] & EF_TYPE):
1409 out += "dissect_%s_%s(gboolean implicit_tag _U_, tvbuff_t *tvb _U_, int offset _U_, asn1_ctx_t *actx _U_, proto_tree *tree _U_, int hf_index _U_) {\n" % (self.eth_type[tname]['proto'], tname)
1411 out += "dissect_%s_%s(tvbuff_t *tvb _U_, int offset _U_, asn1_ctx_t *actx _U_, proto_tree *tree _U_, int hf_index _U_) {\n" % (self.eth_type[tname]['proto'], tname)
1412 #if self.conform.get_fn_presence(tname):
1413 # out += self.conform.get_fn_text(tname, 'FN_HDR')
1415 if self.conform.get_fn_presence(self.eth_type[tname]['ref'][0]):
1416 out += self.conform.get_fn_text(self.eth_type[tname]['ref'][0], 'FN_HDR')
1419 #--- eth_type_fn_ftr --------------------------------------------------------
1420 def eth_type_fn_ftr(self, tname):
1422 #if self.conform.get_fn_presence(tname):
1423 # out += self.conform.get_fn_text(tname, 'FN_FTR')
1425 if self.conform.get_fn_presence(self.eth_type[tname]['ref'][0]):
1426 out += self.conform.get_fn_text(self.eth_type[tname]['ref'][0], 'FN_FTR')
1427 out += " return offset;\n"
1431 #--- eth_type_fn_body -------------------------------------------------------
1432 def eth_type_fn_body(self, tname, body, pars=None):
1434 #if self.conform.get_fn_body_presence(tname):
1435 # out = self.conform.get_fn_text(tname, 'FN_BODY')
1437 if self.conform.get_fn_body_presence(self.eth_type[tname]['ref'][0]):
1438 out = self.conform.get_fn_text(self.eth_type[tname]['ref'][0], 'FN_BODY')
1446 #--- eth_output_hf ----------------------------------------------------------
1447 def eth_output_hf (self):
1448 if not len(self.eth_hf_ord) and not len(self.eth_hfpdu_ord) and not len(self.named_bit): return
1449 fx = self.output.file_open('hf')
1450 for f in (self.eth_hfpdu_ord + self.eth_hf_ord):
1451 fx.write("%-50s/* %s */\n" % ("static int %s = -1; " % (self.eth_hf[f]['fullname']), self.eth_hf[f]['ethtype']))
1452 if (self.named_bit):
1453 fx.write('/* named bits */\n')
1454 for nb in self.named_bit:
1455 fx.write("static int %s = -1;\n" % (nb['ethname']))
1456 self.output.file_close(fx)
1458 #--- eth_output_hf_arr ------------------------------------------------------
1459 def eth_output_hf_arr (self):
1460 if not len(self.eth_hf_ord) and not len(self.eth_hfpdu_ord) and not len(self.named_bit): return
1461 fx = self.output.file_open('hfarr')
1462 for f in (self.eth_hfpdu_ord + self.eth_hf_ord):
1463 t = self.eth_hf[f]['ethtype']
1464 blurb = '"%s.%s"' % (self.eth_type[t]['proto'], t)
1465 attr = self.eth_hf[f]['attr'].copy()
1466 attr['ABBREV'] = '"%s.%s"' % (self.proto, attr['ABBREV'])
1467 if not attr.has_key('BLURB'):
1468 attr['BLURB'] = blurb
1469 fx.write(' { &%s,\n' % (self.eth_hf[f]['fullname']))
1470 fx.write(' { %(NAME)s, %(ABBREV)s,\n' % attr)
1471 fx.write(' %(TYPE)s, %(DISPLAY)s, %(STRINGS)s, %(BITMASK)s,\n' % attr)
1472 fx.write(' %(BLURB)s, HFILL }},\n' % attr)
1473 for nb in self.named_bit:
1475 fx.write(' { &%s,\n' % (nb['ethname']))
1476 fx.write(' { "%s", "%s.%s",\n' % (nb['name'], self.proto, nb['name']))
1477 fx.write(' %s, %s, %s, %s,\n' % (nb['ftype'], nb['display'], nb['strings'], nb['bitmask']))
1478 fx.write(' "%s", HFILL }},\n' % (blurb))
1479 self.output.file_close(fx)
1481 #--- eth_output_ett ---------------------------------------------------------
1482 def eth_output_ett (self):
1483 fx = self.output.file_open('ett')
1485 #fx.write("static gint ett_%s = -1;\n" % (self.eproto))
1486 for t in self.eth_type_ord:
1487 if self.eth_type[t]['tree']:
1488 fx.write("static gint %s = -1;\n" % (self.eth_type[t]['tree']))
1490 self.output.file_close(fx, discard=fempty)
1492 #--- eth_output_ett_arr -----------------------------------------------------
1493 def eth_output_ett_arr(self):
1494 fx = self.output.file_open('ettarr')
1496 #fx.write(" &ett_%s,\n" % (self.eproto))
1497 for t in self.eth_type_ord:
1498 if self.eth_type[t]['tree']:
1499 fx.write(" &%s,\n" % (self.eth_type[t]['tree']))
1501 self.output.file_close(fx, discard=fempty)
1503 #--- eth_output_export ------------------------------------------------------
1504 def eth_output_export(self):
1505 if (not len(self.eth_export_ord)): return
1506 fx = self.output.file_open('exp', ext='h')
1507 for t in self.eth_export_ord: # vals
1508 if (self.eth_type[t]['export'] & EF_ENUM) and self.eth_type[t]['val'].eth_has_enum(t, self):
1509 fx.write(self.eth_type[t]['val'].eth_type_enum(t, self))
1510 if (self.eth_type[t]['export'] & EF_VALS) and self.eth_type[t]['val'].eth_has_vals():
1511 if not self.eth_type[t]['export'] & EF_TABLE:
1512 if self.eth_type[t]['export'] & EF_WS_VAR:
1513 fx.write("WS_VAR_IMPORT ")
1516 fx.write("const value_string %s[];\n" % (self.eth_vals_nm(t)))
1518 fx.write(self.eth_type[t]['val'].eth_type_vals(t, self))
1519 for t in self.eth_export_ord: # functions
1520 if (self.eth_type[t]['export'] & EF_TYPE):
1521 if self.eth_type[t]['export'] & EF_EXTERN:
1523 fx.write(self.eth_type_fn_h(t))
1524 self.output.file_close(fx)
1526 #--- eth_output_expcnf ------------------------------------------------------
1527 def eth_output_expcnf(self):
1528 fx = self.output.file_open('exp', ext='cnf')
1529 fx.write('#.MODULE\n')
1531 for (m, p) in self.modules:
1532 if (len(m) > maxw): maxw = len(m)
1533 for (m, p) in self.modules:
1534 fx.write("%-*s %s\n" % (maxw, m, p))
1535 fx.write('#.END\n\n')
1536 for cls in self.objectclass_ord:
1537 if self.objectclass[cls]['export']:
1538 fx.write('#.CLASS %s\n' % (cls))
1540 for fld in self.objectclass[cls]['val'].fields:
1541 w = len(fld.fld_repr()[0])
1542 if (w > maxw): maxw = w
1543 for fld in self.objectclass[cls]['val'].fields:
1544 repr = fld.fld_repr()
1545 fx.write('%-*s %s\n' % (maxw, repr[0], ' '.join(repr[1:])))
1546 fx.write('#.END\n\n')
1548 fx.write('#.IMPORT_TAG\n')
1549 for t in self.eth_export_ord: # tags
1550 if (self.eth_type[t]['export'] & EF_TYPE):
1551 fx.write('%-24s ' % self.eth_type[t]['ref'][0])
1552 fx.write('%s %s\n' % self.eth_type[t]['val'].GetTag(self))
1553 fx.write('#.END\n\n')
1554 fx.write('#.TYPE_ATTR\n')
1555 for t in self.eth_export_ord: # attributes
1556 if (self.eth_type[t]['export'] & EF_TYPE):
1557 fx.write('%-24s ' % self.eth_type[t]['ref'][0])
1558 attr = self.eth_get_type_attr(self.eth_type[t]['ref'][0]).copy()
1559 fx.write('TYPE = %(TYPE)-9s DISPLAY = %(DISPLAY)-9s STRINGS = %(STRINGS)s BITMASK = %(BITMASK)s\n' % attr)
1560 fx.write('#.END\n\n')
1561 self.output.file_close(fx, keep_anyway=True)
1563 #--- eth_output_val ------------------------------------------------------
1564 def eth_output_val(self):
1565 if (not len(self.eth_value_ord1)): return
1566 fx = self.output.file_open('val', ext='h')
1567 for v in self.eth_value_ord1:
1568 vv = self.eth_value[v]['value']
1569 if isinstance (vv, Value):
1570 vv = vv.to_str(self)
1571 fx.write("#define %-30s %s\n" % (v, vv))
1572 for t in self.eth_type_ord1:
1573 if self.eth_type[t]['import']:
1575 if self.eth_type[t]['val'].eth_has_enum(t, self) and not (self.eth_type[t]['export'] & EF_ENUM):
1576 fx.write(self.eth_type[t]['val'].eth_type_enum(t, self))
1577 self.output.file_close(fx)
1579 #--- eth_output_valexp ------------------------------------------------------
1580 def eth_output_valexp(self):
1581 if (not len(self.eth_vexport_ord)): return
1582 fx = self.output.file_open('valexp', ext='h')
1583 for v in self.eth_vexport_ord:
1584 vv = self.eth_value[v]['value']
1585 if isinstance (vv, Value):
1586 vv = vv.to_str(self)
1587 fx.write("#define %-30s %s\n" % (v, vv))
1588 self.output.file_close(fx)
1590 #--- eth_output_types -------------------------------------------------------
1591 def eth_output_types(self):
1593 t = self.eth_hf[f]['ethtype']
1596 for r in self.eth_hf[f]['ref']:
1597 x[self.field[r]['impl']] = self.field[r]['impl']
1611 if (i): postfix = '_impl'; impl = 'TRUE'
1612 else: postfix = ''; impl = 'FALSE'
1613 out += 'static int dissect_'+f+postfix+'(proto_tree *tree _U_, tvbuff_t *tvb _U_, int offset _U_, asn1_ctx_t *actx _U_) {\n'
1614 par=((impl, 'tvb', 'offset', 'actx', 'tree', self.eth_hf[f]['fullname']),)
1616 out += 'static int dissect_'+f+'(tvbuff_t *tvb _U_, int offset _U_, asn1_ctx_t *actx _U_, proto_tree *tree _U_) {\n'
1617 par=(('tvb', 'offset', 'actx', 'tree', self.eth_hf[f]['fullname']),)
1618 out += self.eth_fn_call('dissect_%s_%s' % (self.eth_type[t]['proto'], t), ret='return',
1623 def out_pdu_decl(f):
1624 t = self.eth_hf[f]['ethtype']
1625 is_new = self.eth_hf[f]['pdu']['new']
1631 out += ' dissect_'+f+'(tvbuff_t *tvb _U_, packet_info *pinfo _U_, proto_tree *tree _U_);\n'
1635 t = self.eth_hf[f]['ethtype']
1636 is_new = self.eth_hf[f]['pdu']['new']
1643 out += ' dissect_'+f+'(tvbuff_t *tvb _U_, packet_info *pinfo _U_, proto_tree *tree _U_) {\n'
1645 out += ' int offset = 0;\n'
1652 if (self.Aligned()):
1656 out += " asn1_ctx_t asn1_ctx;\n"
1657 out += self.eth_fn_call('asn1_ctx_init', par=(('&asn1_ctx', 'ASN1_ENC_PER', aligned, 'pinfo'),))
1659 out += " asn1_ctx_t asn1_ctx;\n"
1660 out += self.eth_fn_call('asn1_ctx_init', par=(('&asn1_ctx', 'ASN1_ENC_BER', 'TRUE', 'pinfo'),))
1661 par=((impl, 'tvb', off_par,'&asn1_ctx', 'tree', self.eth_hf[f]['fullname']),)
1663 par=(('tvb', off_par, '&asn1_ctx', 'tree', self.eth_hf[f]['fullname']),)
1666 out += self.eth_fn_call('dissect_%s_%s' % (self.eth_type[t]['proto'], t), ret=ret_par, par=par)
1667 if (self.Per() and is_new):
1668 out += ' offset += 7; offset >>= 3;\n'
1670 out += ' return offset;\n'
1674 fx = self.output.file_open('fn')
1676 if (len(self.eth_hfpdu_ord)):
1678 for f in self.eth_hfpdu_ord:
1679 if (self.eth_hf[f]['pdu'] and self.eth_hf[f]['pdu']['need_decl']):
1681 fx.write('/*--- PDUs declarations ---*/\n')
1683 fx.write(out_pdu_decl(f))
1686 if self.eth_dep_cycle:
1687 fx.write('/*--- Cyclic dependencies ---*/\n\n')
1689 while i < len(self.eth_dep_cycle):
1690 t = self.type[self.eth_dep_cycle[i][0]]['ethname']
1691 if self.dep_cycle_eth_type[t][0] != i: i += 1; continue
1692 fx.write(''.join(map(lambda i: '/* %s */\n' % ' -> '.join(self.eth_dep_cycle[i]), self.dep_cycle_eth_type[t])))
1693 fx.write(self.eth_type_fn_h(t))
1694 if (self.Fld() or self.eth_type[t]['create_field']):
1696 for f in self.eth_hf_ord:
1697 if ((self.eth_hf[f]['ethtype'] == t) and (self.Fld() or self.eth_hf[f]['create_field'])):
1698 fx.write(out_field(f))
1702 if (self.Fld()): # fields for imported types
1703 fx.write('/*--- Fields for imported types ---*/\n\n')
1704 for f in self.eth_hf_ord:
1705 if (self.eth_type[self.eth_hf[f]['ethtype']]['import']):
1706 fx.write(out_field(f))
1708 for t in self.eth_type_ord1:
1709 if self.eth_type[t]['import']:
1711 if self.eth_type[t]['val'].eth_has_vals():
1712 if self.eth_type[t]['no_emit'] & EF_VALS:
1714 elif self.eth_type[t]['user_def'] & EF_VALS:
1715 fx.write("extern const value_string %s[];\n" % (self.eth_vals_nm(t)))
1716 elif (self.eth_type[t]['export'] & EF_VALS) and (self.eth_type[t]['export'] & EF_TABLE):
1719 fx.write(self.eth_type[t]['val'].eth_type_vals(t, self))
1720 if self.eth_type[t]['no_emit'] & EF_TYPE:
1722 elif self.eth_type[t]['user_def'] & EF_TYPE:
1723 fx.write(self.eth_type_fn_h(t))
1725 fx.write(self.eth_type[t]['val'].eth_type_fn(self.eth_type[t]['proto'], t, self))
1726 if ((self.Fld() or self.eth_type[t]['create_field']) and not self.dep_cycle_eth_type.has_key(t)):
1727 for f in self.eth_hf_ord:
1728 if ((self.eth_hf[f]['ethtype'] == t) and (self.Fld() or self.eth_hf[f]['create_field'])):
1729 fx.write(out_field(f))
1731 if (len(self.eth_hfpdu_ord)):
1732 fx.write('/*--- PDUs ---*/\n\n')
1733 for f in self.eth_hfpdu_ord:
1734 if (self.eth_hf[f]['pdu']):
1735 if (self.emitted_pdu.has_key(f)):
1736 fx.write(" /* %s already emitted */\n" % (f))
1738 fx.write(out_pdu(f))
1739 self.emitted_pdu[f] = True
1741 fempty = pos == fx.tell()
1742 self.output.file_close(fx, discard=fempty)
1744 #--- eth_output_dis_hnd -----------------------------------------------------
1745 def eth_output_dis_hnd(self):
1746 fx = self.output.file_open('dis-hnd')
1748 for f in self.eth_hfpdu_ord:
1749 pdu = self.eth_hf[f]['pdu']
1750 if (pdu and pdu['reg'] and not pdu['hidden']):
1752 if (pdu['reg'] != '.'):
1753 dis += '.' + pdu['reg']
1754 fx.write('static dissector_handle_t %s_handle;\n' % (asn2c(dis)))
1757 self.output.file_close(fx, discard=fempty)
1759 #--- eth_output_dis_reg -----------------------------------------------------
1760 def eth_output_dis_reg(self):
1761 fx = self.output.file_open('dis-reg')
1763 for f in self.eth_hfpdu_ord:
1764 pdu = self.eth_hf[f]['pdu']
1765 if (pdu and pdu['reg']):
1767 if (pdu['new']): new_prefix = 'new_'
1769 if (pdu['reg'] != '.'): dis += '.' + pdu['reg']
1770 fx.write(' %sregister_dissector("%s", dissect_%s, proto_%s);\n' % (new_prefix, dis, f, self.eproto))
1771 if (not pdu['hidden']):
1772 fx.write(' %s_handle = find_dissector("%s");\n' % (asn2c(dis), dis))
1775 self.output.file_close(fx, discard=fempty)
1777 #--- eth_output_dis_tab -----------------------------------------------------
1778 def eth_output_dis_tab(self):
1779 fx = self.output.file_open('dis-tab')
1781 for k in self.conform.get_order('REGISTER'):
1782 reg = self.conform.use_item('REGISTER', k)
1783 if not self.field.has_key(reg['pdu']): continue
1784 f = self.field[reg['pdu']]['ethname']
1785 pdu = self.eth_hf[f]['pdu']
1787 if (pdu['new']): new_prefix = 'new_'
1788 if (reg['rtype'] in ('NUM', 'STR')):
1790 if (reg['rtype'] == 'STR'): rstr = '_string'
1793 if (pdu['reg'] != '.'): dis += '.' + pdu['reg']
1794 if (not pdu['hidden']):
1795 hnd = '%s_handle' % (asn2c(dis))
1797 hnd = 'find_dissector("%s")' % (dis)
1799 hnd = '%screate_dissector_handle(dissect_%s, proto_%s)' % (new_prefix, f, self.eproto)
1800 rport = self.value_get_eth(reg['rport'])
1801 fx.write(' dissector_add%s("%s", %s, %s);\n' % (rstr, reg['rtable'], rport, hnd))
1802 elif (reg['rtype'] in ('BER', 'PER')):
1803 roid = self.value_get_eth(reg['roid'])
1804 fx.write(' %sregister_%s_oid_dissector(%s, dissect_%s, proto_%s, %s);\n' % (new_prefix, reg['rtype'].lower(), roid, f, self.eproto, reg['roidname']))
1807 self.output.file_close(fx, discard=fempty)
1809 #--- eth_output_table -----------------------------------------------------
1810 def eth_output_table(self):
1811 for num in self.conform.report.keys():
1812 fx = self.output.file_open('table' + num)
1813 for rep in self.conform.report[num]:
1814 if rep['type'] == 'HDR':
1818 var_list = var.split('.')
1821 if (self.oassign_cls.has_key(cls)):
1822 for ident in self.oassign_cls[cls]:
1823 obj = self.get_obj_repr(ident, var_list)
1827 obj['_DICT'] = str(obj)
1829 text = rep['text'] % obj
1831 raise sys.exc_type, "%s:%s invalid key %s for information object %s of %s" % (rep['fn'], rep['lineno'], sys.exc_value, ident, var)
1834 fx.write("/* Unknown or empty loop list %s */\n" % (var))
1836 fx.write(rep['text'])
1837 if rep['type'] == 'FTR':
1839 self.output.file_close(fx)
1841 #--- dupl_report -----------------------------------------------------
1842 def dupl_report(self):
1844 tmplist = self.eth_type_dupl.keys()
1847 msg = "The same type names for different types. Explicit type renaming is recommended.\n"
1849 for tt in self.eth_type_dupl[t]:
1850 msg += " %-20s %s\n" % (self.type[tt]['ethname'], tt)
1851 warnings.warn_explicit(msg, UserWarning, '', '')
1853 tmplist = self.eth_hf_dupl.keys()
1856 msg = "The same field names for different types. Explicit field renaming is recommended.\n"
1858 for tt in self.eth_hf_dupl[f].keys():
1859 msg += " %-20s %-20s " % (self.eth_hf_dupl[f][tt], tt)
1860 msg += ", ".join(self.eth_hf[self.eth_hf_dupl[f][tt]]['ref'])
1862 warnings.warn_explicit(msg, UserWarning, '', '')
1864 #--- eth_do_output ------------------------------------------------------------
1865 def eth_do_output(self):
1867 print "\n# Assignments"
1868 for a in self.assign_ord:
1870 if (self.assign[a]['virt']): v = '*'
1872 print "\n# Value assignments"
1873 for a in self.vassign_ord:
1875 print "\n# Information object assignments"
1876 for a in self.oassign_ord:
1877 print " %-12s (%s)" % (a, self.oassign[a].cls)
1879 print "\n# Imported Types"
1880 print "%-40s %-24s %-24s" % ("ASN.1 name", "Module", "Protocol")
1882 for t in self.type_imp:
1883 print "%-40s %-24s %-24s" % (t, self.type[t]['import'], self.type[t]['proto'])
1884 print "\n# Imported Values"
1885 print "%-40s %-24s %-24s" % ("ASN.1 name", "Module", "Protocol")
1887 for t in self.value_imp:
1888 print "%-40s %-24s %-24s" % (t, self.value[t]['import'], self.value[t]['proto'])
1889 print "\n# Imported Object Classes"
1890 print "%-40s %-24s %-24s" % ("ASN.1 name", "Module", "Protocol")
1892 for t in self.objectclass_imp:
1893 print "%-40s %-24s %-24s" % (t, self.objectclass[t]['import'], self.objectclass[t]['proto'])
1894 print "\n# Exported Types"
1895 print "%-31s %s" % ("Wireshark type", "Export Flag")
1897 for t in self.eth_export_ord:
1898 print "%-31s 0x%02X" % (t, self.eth_type[t]['export'])
1899 print "\n# Exported Values"
1900 print "%-40s %s" % ("Wireshark name", "Value")
1902 for v in self.eth_vexport_ord:
1903 vv = self.eth_value[v]['value']
1904 if isinstance (vv, Value):
1905 vv = vv.to_str(self)
1906 print "%-40s %s" % (v, vv)
1907 print "\n# ASN.1 Object Classes"
1908 print "%-40s %-24s %-24s" % ("ASN.1 name", "Module", "Protocol")
1910 for t in self.objectclass_ord:
1911 print "%-40s " % (t)
1912 print "\n# ASN.1 Types"
1913 print "%-49s %-24s %-24s" % ("ASN.1 unique name", "'tname'", "Wireshark type")
1915 for t in self.type_ord:
1916 print "%-49s %-24s %-24s" % (t, self.type[t]['tname'], self.type[t]['ethname'])
1917 print "\n# Wireshark Types"
1918 print "Wireshark type References (ASN.1 types)"
1920 for t in self.eth_type_ord:
1921 print "%-31s %d" % (t, len(self.eth_type[t]['ref'])),
1922 print ', '.join(self.eth_type[t]['ref'])
1923 print "\n# ASN.1 Values"
1924 print "%-40s %-18s %-20s %s" % ("ASN.1 unique name", "Type", "Value", "Wireshark value")
1926 for v in self.value_ord:
1927 vv = self.value[v]['value']
1928 if isinstance (vv, Value):
1929 vv = vv.to_str(self)
1930 print "%-40s %-18s %-20s %s" % (v, self.value[v]['type'].eth_tname(), vv, self.value[v]['ethname'])
1931 #print "\n# Wireshark Values"
1932 #print "%-40s %s" % ("Wireshark name", "Value")
1934 #for v in self.eth_value_ord:
1935 # vv = self.eth_value[v]['value']
1936 # if isinstance (vv, Value):
1937 # vv = vv.to_str(self)
1938 # print "%-40s %s" % (v, vv)
1939 print "\n# ASN.1 Fields"
1940 print "ASN.1 unique name Wireshark name ASN.1 type"
1942 for f in (self.pdu_ord + self.field_ord):
1943 print "%-40s %-20s %s" % (f, self.field[f]['ethname'], self.field[f]['type'])
1944 print "\n# Wireshark Fields"
1945 print "Wireshark name Wireshark type References (ASN.1 fields)"
1947 for f in (self.eth_hfpdu_ord + self.eth_hf_ord):
1948 print "%-30s %-20s %s" % (f, self.eth_hf[f]['ethtype'], len(self.eth_hf[f]['ref'])),
1949 print ', '.join(self.eth_hf[f]['ref'])
1950 #print "\n# Order after dependencies"
1951 #print '\n'.join(self.eth_type_ord1)
1952 print "\n# Cyclic dependencies"
1953 for c in self.eth_dep_cycle:
1954 print ' -> '.join(c)
1956 self.output.outnm = self.outnm_opt
1957 if (not self.output.outnm):
1958 self.output.outnm = self.proto
1959 self.output.outnm = self.output.outnm.replace('.', '-')
1960 self.eth_output_hf()
1961 self.eth_output_ett()
1962 self.eth_output_types()
1963 self.eth_output_hf_arr()
1964 self.eth_output_ett_arr()
1965 self.eth_output_export()
1967 self.eth_output_expcnf()
1968 self.eth_output_val()
1969 self.eth_output_valexp()
1970 self.eth_output_dis_hnd()
1971 self.eth_output_dis_reg()
1972 self.eth_output_dis_tab()
1973 self.eth_output_table()
1975 def dbg_modules(self):
1977 print "%-30s " % (m),
1978 dep = self.module[m][:]
1979 for i in range(len(dep)):
1980 if not self.module.has_key(dep[i]):
1981 dep[i] = '*' + dep[i]
1982 print ', '.join(dep)
1983 # end of print_mod()
1984 (mod_ord, mod_cyc) = dependency_compute(self.module_ord, self.module, ignore_fn = lambda t: not self.module.has_key(t))
1985 print "\n# ASN.1 Moudules"
1986 print "Module name Dependency"
1989 for m in (self.module_ord):
1991 new_ord = new_ord or (self.module_ord.index(m) != mod_ord.index(m))
1993 print "\n# ASN.1 Moudules - in dependency order"
1994 print "Module name Dependency"
1999 print "\nCyclic dependencies:"
2000 for i in (range(len(mod_cyc))):
2001 print "%02d: %s" % (i + 1, str(mod_cyc[i]))
2004 #--- EthCnf -------------------------------------------------------------------
2013 self.suppress_line = False
2014 self.include_path = []
2015 # Value name Default value Duplicity check Usage check
2016 self.tblcfg['EXPORTS'] = { 'val_nm' : 'flag', 'val_dflt' : 0, 'chk_dup' : True, 'chk_use' : True }
2017 self.tblcfg['MAKE_ENUM'] = { 'val_nm' : 'flag', 'val_dflt' : 0, 'chk_dup' : True, 'chk_use' : True }
2018 self.tblcfg['PDU'] = { 'val_nm' : 'attr', 'val_dflt' : None, 'chk_dup' : True, 'chk_use' : True }
2019 self.tblcfg['REGISTER'] = { 'val_nm' : 'attr', 'val_dflt' : None, 'chk_dup' : True, 'chk_use' : True }
2020 self.tblcfg['USER_DEFINED'] = { 'val_nm' : 'flag', 'val_dflt' : 0, 'chk_dup' : True, 'chk_use' : True }
2021 self.tblcfg['NO_EMIT'] = { 'val_nm' : 'flag', 'val_dflt' : 0, 'chk_dup' : True, 'chk_use' : True }
2022 self.tblcfg['MODULE'] = { 'val_nm' : 'proto', 'val_dflt' : None, 'chk_dup' : True, 'chk_use' : False }
2023 self.tblcfg['OMIT_ASSIGNMENT'] = { 'val_nm' : 'omit', 'val_dflt' : False, 'chk_dup' : True, 'chk_use' : True }
2024 self.tblcfg['NO_OMIT_ASSGN'] = { 'val_nm' : 'omit', 'val_dflt' : True, 'chk_dup' : True, 'chk_use' : True }
2025 self.tblcfg['VIRTUAL_ASSGN'] = { 'val_nm' : 'name', 'val_dflt' : None, 'chk_dup' : True, 'chk_use' : True }
2026 self.tblcfg['SET_TYPE'] = { 'val_nm' : 'type', 'val_dflt' : None, 'chk_dup' : True, 'chk_use' : True }
2027 self.tblcfg['TYPE_RENAME'] = { 'val_nm' : 'eth_name', 'val_dflt' : None, 'chk_dup' : True, 'chk_use' : True }
2028 self.tblcfg['FIELD_RENAME'] = { 'val_nm' : 'eth_name', 'val_dflt' : None, 'chk_dup' : True, 'chk_use' : True }
2029 self.tblcfg['IMPORT_TAG'] = { 'val_nm' : 'ttag', 'val_dflt' : (), 'chk_dup' : True, 'chk_use' : False }
2030 self.tblcfg['FN_PARS'] = { 'val_nm' : 'pars', 'val_dflt' : {}, 'chk_dup' : True, 'chk_use' : True }
2031 self.tblcfg['TYPE_ATTR'] = { 'val_nm' : 'attr', 'val_dflt' : {}, 'chk_dup' : True, 'chk_use' : False }
2032 self.tblcfg['ETYPE_ATTR'] = { 'val_nm' : 'attr', 'val_dflt' : {}, 'chk_dup' : True, 'chk_use' : False }
2033 self.tblcfg['FIELD_ATTR'] = { 'val_nm' : 'attr', 'val_dflt' : {}, 'chk_dup' : True, 'chk_use' : True }
2034 self.tblcfg['EFIELD_ATTR'] = { 'val_nm' : 'attr', 'val_dflt' : {}, 'chk_dup' : True, 'chk_use' : True }
2035 self.tblcfg['ASSIGNED_ID'] = { 'val_nm' : 'ids', 'val_dflt' : {}, 'chk_dup' : False,'chk_use' : False }
2038 for k in self.tblcfg.keys() :
2042 def add_item(self, table, key, fn, lineno, **kw):
2043 if self.tblcfg[table]['chk_dup'] and self.table[table].has_key(key):
2044 warnings.warn_explicit("Duplicated %s for %s. Previous one is at %s:%d" %
2045 (table, key, self.table[table][key]['fn'], self.table[table][key]['lineno']),
2046 UserWarning, fn, lineno)
2048 self.table[table][key] = {'fn' : fn, 'lineno' : lineno, 'used' : False}
2049 self.table[table][key].update(kw)
2050 self.order[table].append(key)
2052 def update_item(self, table, key, fn, lineno, **kw):
2053 if not self.table[table].has_key(key):
2054 self.table[table][key] = {'fn' : fn, 'lineno' : lineno, 'used' : False}
2055 self.order[table].append(key)
2056 self.table[table][key][self.tblcfg[table]['val_nm']] = {}
2057 self.table[table][key][self.tblcfg[table]['val_nm']].update(kw[self.tblcfg[table]['val_nm']])
2059 def get_order(self, table):
2060 return self.order[table]
2062 def check_item(self, table, key):
2063 return self.table[table].has_key(key)
2065 def check_item_value(self, table, key, **kw):
2066 return self.table[table].has_key(key) and self.table[table][key].has_key(kw.get('val_nm', self.tblcfg[table]['val_nm']))
2068 def use_item(self, table, key, **kw):
2069 vdflt = kw.get('val_dflt', self.tblcfg[table]['val_dflt'])
2070 if not self.table[table].has_key(key): return vdflt
2071 vname = kw.get('val_nm', self.tblcfg[table]['val_nm'])
2072 #print "use_item() - set used for %s %s" % (table, key)
2073 self.table[table][key]['used'] = True
2074 return self.table[table][key].get(vname, vdflt)
2076 def omit_assignment(self, type, ident, module):
2077 if self.ectx.conform.use_item('OMIT_ASSIGNMENT', ident):
2079 if self.ectx.conform.use_item('OMIT_ASSIGNMENT', '*') or \
2080 self.ectx.conform.use_item('OMIT_ASSIGNMENT', '*'+type) or \
2081 self.ectx.conform.use_item('OMIT_ASSIGNMENT', '*/'+module) or \
2082 self.ectx.conform.use_item('OMIT_ASSIGNMENT', '*'+type+'/'+module):
2083 return self.ectx.conform.use_item('NO_OMIT_ASSGN', ident)
2086 def add_fn_line(self, name, ctx, line, fn, lineno):
2087 if not self.fn.has_key(name):
2088 self.fn[name] = {'FN_HDR' : None, 'FN_FTR' : None, 'FN_BODY' : None}
2089 if (self.fn[name][ctx]):
2090 self.fn[name][ctx]['text'] += line
2092 self.fn[name][ctx] = {'text' : line, 'used' : False,
2093 'fn' : fn, 'lineno' : lineno}
2094 def get_fn_presence(self, name):
2095 #print "get_fn_presence('%s'):%s" % (name, str(self.fn.has_key(name)))
2096 #if self.fn.has_key(name): print self.fn[name]
2097 return self.fn.has_key(name)
2098 def get_fn_body_presence(self, name):
2099 return self.fn.has_key(name) and self.fn[name]['FN_BODY']
2100 def get_fn_text(self, name, ctx):
2101 if (not self.fn.has_key(name)):
2103 if (not self.fn[name][ctx]):
2105 self.fn[name][ctx]['used'] = True
2106 out = self.fn[name][ctx]['text']
2107 if (not self.suppress_line):
2108 out = '#line %u "%s"\n%s\n' % (self.fn[name][ctx]['lineno'], self.fn[name][ctx]['fn'], out);
2111 def add_pdu(self, par, is_new, fn, lineno):
2112 #print "add_pdu(par=%s, %s, %d)" % (str(par), fn, lineno)
2113 (reg, hidden) = (None, False)
2114 if (len(par) > 1): reg = par[1]
2115 if (reg and reg[0]=='@'): (reg, hidden) = (reg[1:], True)
2116 attr = {'new' : is_new, 'reg' : reg, 'hidden' : hidden, 'need_decl' : False}
2117 self.add_item('PDU', par[0], attr=attr, fn=fn, lineno=lineno)
2120 def add_register(self, pdu, par, fn, lineno):
2121 #print "add_register(pdu=%s, par=%s, %s, %d)" % (pdu, str(par), fn, lineno)
2122 if (par[0] in ('N', 'NUM')): rtype = 'NUM'; (pmin, pmax) = (2, 2)
2123 elif (par[0] in ('S', 'STR')): rtype = 'STR'; (pmin, pmax) = (2, 2)
2124 elif (par[0] in ('B', 'BER')): rtype = 'BER'; (pmin, pmax) = (1, 2)
2125 elif (par[0] in ('P', 'PER')): rtype = 'PER'; (pmin, pmax) = (1, 2)
2126 else: warnings.warn_explicit("Unknown registration type '%s'" % (par[2]), UserWarning, fn, lineno); return
2127 if ((len(par)-1) < pmin):
2128 warnings.warn_explicit("Too few parameters for %s registration type. At least %d parameters are required" % (rtype, pmin), UserWarning, fn, lineno)
2130 if ((len(par)-1) > pmax):
2131 warnings.warn_explicit("Too many parameters for %s registration type. Only %d parameters are allowed" % (rtype, pmax), UserWarning, fn, lineno)
2132 attr = {'pdu' : pdu, 'rtype' : rtype}
2133 if (rtype in ('NUM', 'STR')):
2134 attr['rtable'] = par[1]
2135 attr['rport'] = par[2]
2136 rkey = '/'.join([rtype, attr['rtable'], attr['rport']])
2137 elif (rtype in ('BER', 'PER')):
2138 attr['roid'] = par[1]
2139 attr['roidname'] = '""'
2141 attr['roidname'] = par[2]
2142 elif attr['roid'][0] != '"':
2143 attr['roidname'] = '"' + attr['roid'] + '"'
2144 rkey = '/'.join([rtype, attr['roid']])
2145 self.add_item('REGISTER', rkey, attr=attr, fn=fn, lineno=lineno)
2147 def check_par(self, par, pmin, pmax, fn, lineno):
2148 for i in range(len(par)):
2152 if par[i][0] == '#':
2156 warnings.warn_explicit("Too few parameters. At least %d parameters are required" % (pmin), UserWarning, fn, lineno)
2158 if (pmax >= 0) and (len(par) > pmax):
2159 warnings.warn_explicit("Too many parameters. Only %d parameters are allowed" % (pmax), UserWarning, fn, lineno)
2164 def get_par(line, pmin, pmax, fn, lineno):
2165 par = line.split(None, pmax)
2166 par = self.check_par(par, pmin, pmax, fn, lineno)
2169 def get_par_nm(line, pmin, pmax, fn, lineno):
2171 par = line.split(None, pmax)
2174 for i in range(len(par)):
2175 if par[i][0] == '#':
2179 warnings.warn_explicit("Too few parameters. At least %d parameters are required" % (pmin), UserWarning, fn, lineno)
2186 nmpar_first = re.compile(r'^\s*(?P<attr>[_A-Z][_A-Z0-9]*)\s*=\s*')
2187 nmpar_next = re.compile(r'\s+(?P<attr>[_A-Z][_A-Z0-9]*)\s*=\s*')
2188 nmpar_end = re.compile(r'\s*$')
2189 result = nmpar_first.search(nmpar)
2192 k = result.group('attr')
2194 result = nmpar_next.search(nmpar, pos)
2199 p2 = nmpar_end.search(nmpar, pos).start()
2207 directive = re.compile(r'^\s*#\.(?P<name>[A-Z_][A-Z_0-9]*)\s+')
2208 report = re.compile(r'^TABLE(?P<num>\d*)_(?P<type>HDR|BODY|FTR)$')
2209 comment = re.compile(r'^\s*#[^.]')
2210 empty = re.compile(r'^\s*$')
2214 default_flags = 0x00
2227 fn, f, lineno = frec['fn'], frec['f'], frec['lineno']
2231 if comment.search(line): continue
2232 result = directive.search(line)
2233 if result: # directive
2234 rep_result = report.search(result.group('name'))
2235 if result.group('name') == 'END_OF_CNF':
2237 elif result.group('name') == 'OPT':
2238 ctx = result.group('name')
2239 par = get_par(line[result.end():], 0, -1, fn=fn, lineno=lineno)
2240 if not par: continue
2241 self.set_opt(par[0], par[1:], fn, lineno)
2243 elif result.group('name') in ('PDU', 'PDU_NEW', 'REGISTER', 'REGISTER_NEW',
2244 'MODULE', 'MODULE_IMPORT',
2245 'OMIT_ASSIGNMENT', 'NO_OMIT_ASSGN',
2246 'VIRTUAL_ASSGN', 'SET_TYPE',
2247 'TYPE_RENAME', 'FIELD_RENAME', 'TF_RENAME', 'IMPORT_TAG',
2248 'TYPE_ATTR', 'ETYPE_ATTR', 'FIELD_ATTR', 'EFIELD_ATTR'):
2249 ctx = result.group('name')
2250 elif result.group('name') in ('OMIT_ALL_ASSIGNMENTS', 'OMIT_ASSIGNMENTS_EXCEPT',
2251 'OMIT_ALL_TYPE_ASSIGNMENTS', 'OMIT_TYPE_ASSIGNMENTS_EXCEPT',
2252 'OMIT_ALL_VALUE_ASSIGNMENTS', 'OMIT_VALUE_ASSIGNMENTS_EXCEPT'):
2253 ctx = result.group('name')
2255 if ctx in ('OMIT_ALL_TYPE_ASSIGNMENTS', 'OMIT_TYPE_ASSIGNMENTS_EXCEPT'):
2257 if ctx in ('OMIT_ALL_VALUE_ASSIGNMENTS', 'OMIT_VALUE_ASSIGNMENTS_EXCEPT'):
2259 par = get_par(line[result.end():], 0, 1, fn=fn, lineno=lineno)
2262 self.add_item('OMIT_ASSIGNMENT', key, omit=True, fn=fn, lineno=lineno)
2263 if ctx in ('OMIT_ASSIGNMENTS_EXCEPT', 'OMIT_TYPE_ASSIGNMENTS_EXCEPT', 'OMIT_VALUE_ASSIGNMENTS_EXCEPT'):
2264 ctx = 'NO_OMIT_ASSGN'
2267 elif result.group('name') in ('EXPORTS', 'USER_DEFINED', 'NO_EMIT'):
2268 ctx = result.group('name')
2269 default_flags = EF_TYPE|EF_VALS
2270 if ctx == 'EXPORTS':
2271 par = get_par(line[result.end():], 0, 5, fn=fn, lineno=lineno)
2273 par = get_par(line[result.end():], 0, 1, fn=fn, lineno=lineno)
2274 if not par: continue
2276 if (par[0] == 'WITH_VALS'): default_flags |= EF_TYPE|EF_VALS
2277 elif (par[0] == 'WITHOUT_VALS'): default_flags |= EF_TYPE; default_flags &= ~EF_TYPE
2278 elif (par[0] == 'ONLY_VALS'): default_flags &= ~EF_TYPE; default_flags |= EF_VALS
2279 elif (ctx == 'EXPORTS'): p = 0
2280 else: warnings.warn_explicit("Unknown parameter value '%s'" % (par[0]), UserWarning, fn, lineno)
2281 for i in range(p, len(par)):
2282 if (par[i] == 'ONLY_ENUM'): default_flags &= ~(EF_TYPE|EF_VALS); default_flags |= EF_ENUM
2283 elif (par[i] == 'WITH_ENUM'): default_flags |= EF_ENUM
2284 elif (par[i] == 'VALS_WITH_TABLE'): default_flags |= EF_TABLE
2285 elif (par[i] == 'WS_VAR'): default_flags |= EF_WS_VAR
2286 elif (par[i] == 'EXTERN'): default_flags |= EF_EXTERN
2287 elif (par[i] == 'NO_PROT_PREFIX'): default_flags |= EF_NO_PROT
2288 else: warnings.warn_explicit("Unknown parameter value '%s'" % (par[i]), UserWarning, fn, lineno)
2289 elif result.group('name') in ('MAKE_ENUM', 'MAKE_DEFINES'):
2290 ctx = result.group('name')
2291 default_flags = EF_ENUM
2292 if ctx == 'MAKE_ENUM': default_flags |= EF_NO_PROT|EF_NO_TYPE
2293 if ctx == 'MAKE_DEFINES': default_flags |= EF_DEFINE|EF_UCASE|EF_NO_TYPE
2294 par = get_par(line[result.end():], 0, 3, fn=fn, lineno=lineno)
2295 for i in range(0, len(par)):
2296 if (par[i] == 'NO_PROT_PREFIX'): default_flags |= EF_NO_PROT
2297 elif (par[i] == 'NO_TYPE_PREFIX'): default_flags |= EF_NO_TYPE
2298 elif (par[i] == 'UPPER_CASE'): default_flags |= EF_UCASE
2299 elif (par[i] == 'NO_UPPER_CASE'): default_flags &= ~EF_UCASE
2300 else: warnings.warn_explicit("Unknown parameter value '%s'" % (par[i]), UserWarning, fn, lineno)
2301 elif result.group('name') in ('FN_HDR', 'FN_FTR'):
2302 par = get_par(line[result.end():], 1, 1, fn=fn, lineno=lineno)
2303 if not par: continue
2304 ctx = result.group('name')
2306 elif result.group('name') == 'FN_BODY':
2307 par = get_par_nm(line[result.end():], 1, 1, fn=fn, lineno=lineno)
2308 if not par: continue
2309 ctx = result.group('name')
2312 self.add_item('FN_PARS', name, pars=par[1], fn=fn, lineno=lineno)
2313 elif result.group('name') == 'FN_PARS':
2314 par = get_par_nm(line[result.end():], 0, 1, fn=fn, lineno=lineno)
2315 ctx = result.group('name')
2320 self.add_item(ctx, name, pars={}, fn=fn, lineno=lineno)
2322 self.add_item(ctx, par[0], pars=par[1], fn=fn, lineno=lineno)
2324 elif result.group('name') == 'CLASS':
2325 par = get_par(line[result.end():], 1, 1, fn=fn, lineno=lineno)
2326 if not par: continue
2327 ctx = result.group('name')
2329 add_class_ident(name)
2330 if not name.isupper():
2331 warnings.warn_explicit("No lower-case letters shall be included in information object class name (%s)" % (name),
2332 UserWarning, fn, lineno)
2333 elif result.group('name') == 'ASSIGNED_OBJECT_IDENTIFIER':
2334 par = get_par(line[result.end():], 1, 1, fn=fn, lineno=lineno)
2335 if not par: continue
2336 self.update_item('ASSIGNED_ID', 'OBJECT_IDENTIFIER', ids={par[0] : par[0]}, fn=fn, lineno=lineno)
2337 elif rep_result: # Reports
2338 num = rep_result.group('num')
2339 type = rep_result.group('type')
2341 par = get_par(line[result.end():], 1, 1, fn=fn, lineno=lineno)
2342 if not par: continue
2344 par = get_par(line[result.end():], 0, 0, fn=fn, lineno=lineno)
2345 rep = { 'type' : type, 'var' : None, 'text' : '', 'fn' : fn, 'lineno' : lineno }
2348 self.report.setdefault(num, []).append(rep)
2351 elif result.group('name') == 'INCLUDE':
2352 par = get_par(line[result.end():], 1, 1, fn=fn, lineno=lineno)
2354 warnings.warn_explicit("INCLUDE requires parameter", UserWarning, fn, lineno)
2357 #print "Try include: %s" % (fname)
2358 if (not os.path.exists(fname)):
2359 fname = os.path.join(os.path.split(fn)[0], par[0])
2360 #print "Try include: %s" % (fname)
2362 while not os.path.exists(fname) and (i < len(self.include_path)):
2363 fname = os.path.join(self.include_path[i], par[0])
2364 #print "Try include: %s" % (fname)
2366 if (not os.path.exists(fname)):
2368 fnew = open(fname, "r")
2369 stack.append({'fn' : fn, 'f' : f, 'lineno' : lineno})
2370 fn, f, lineno = par[0], fnew, 0
2371 elif result.group('name') == 'END':
2374 warnings.warn_explicit("Unknown directive '%s'" % (result.group('name')), UserWarning, fn, lineno)
2377 if not empty.match(line):
2378 warnings.warn_explicit("Non-empty line in empty context", UserWarning, fn, lineno)
2380 if empty.match(line): continue
2381 par = get_par(line, 1, -1, fn=fn, lineno=lineno)
2382 if not par: continue
2383 self.set_opt(par[0], par[1:], fn, lineno)
2384 elif ctx in ('EXPORTS', 'USER_DEFINED', 'NO_EMIT'):
2385 if empty.match(line): continue
2386 if ctx == 'EXPORTS':
2387 par = get_par(line, 1, 6, fn=fn, lineno=lineno)
2389 par = get_par(line, 1, 2, fn=fn, lineno=lineno)
2390 if not par: continue
2391 flags = default_flags
2394 if (par[1] == 'WITH_VALS'): flags |= EF_TYPE|EF_VALS
2395 elif (par[1] == 'WITHOUT_VALS'): flags |= EF_TYPE; flags &= ~EF_TYPE
2396 elif (par[1] == 'ONLY_VALS'): flags &= ~EF_TYPE; flags |= EF_VALS
2397 elif (ctx == 'EXPORTS'): p = 1
2398 else: warnings.warn_explicit("Unknown parameter value '%s'" % (par[1]), UserWarning, fn, lineno)
2399 for i in range(p, len(par)):
2400 if (par[i] == 'ONLY_ENUM'): flags &= ~(EF_TYPE|EF_VALS); flags |= EF_ENUM
2401 elif (par[i] == 'WITH_ENUM'): flags |= EF_ENUM
2402 elif (par[i] == 'VALS_WITH_TABLE'): flags |= EF_TABLE
2403 elif (par[i] == 'WS_VAR'): flags |= EF_WS_VAR
2404 elif (par[i] == 'EXTERN'): flags |= EF_EXTERN
2405 elif (par[i] == 'NO_PROT_PREFIX'): flags |= EF_NO_PROT
2406 else: warnings.warn_explicit("Unknown parameter value '%s'" % (par[i]), UserWarning, fn, lineno)
2407 self.add_item(ctx, par[0], flag=flags, fn=fn, lineno=lineno)
2408 elif ctx in ('MAKE_ENUM', 'MAKE_DEFINES'):
2409 if empty.match(line): continue
2410 par = get_par(line, 1, 4, fn=fn, lineno=lineno)
2411 if not par: continue
2412 flags = default_flags
2413 for i in range(1, len(par)):
2414 if (par[i] == 'NO_PROT_PREFIX'): flags |= EF_NO_PROT
2415 elif (par[i] == 'NO_TYPE_PREFIX'): flags |= EF_NO_TYPE
2416 elif (par[i] == 'UPPER_CASE'): flags |= EF_UCASE
2417 elif (par[i] == 'NO_UPPER_CASE'): flags &= ~EF_UCASE
2418 else: warnings.warn_explicit("Unknown parameter value '%s'" % (par[i]), UserWarning, fn, lineno)
2419 self.add_item('MAKE_ENUM', par[0], flag=flags, fn=fn, lineno=lineno)
2420 elif ctx in ('PDU', 'PDU_NEW'):
2421 if empty.match(line): continue
2422 par = get_par(line, 1, 5, fn=fn, lineno=lineno)
2423 if not par: continue
2425 if (ctx == 'PDU_NEW'): is_new = True
2426 self.add_pdu(par[0:2], is_new, fn, lineno)
2428 self.add_register(par[0], par[2:5], fn, lineno)
2429 elif ctx in ('REGISTER', 'REGISTER_NEW'):
2430 if empty.match(line): continue
2431 par = get_par(line, 3, 4, fn=fn, lineno=lineno)
2432 if not par: continue
2433 if not self.check_item('PDU', par[0]):
2435 if (ctx == 'REGISTER_NEW'): is_new = True
2436 self.add_pdu(par[0:1], is_new, fn, lineno)
2437 self.add_register(par[0], par[1:4], fn, lineno)
2438 elif ctx in ('MODULE', 'MODULE_IMPORT'):
2439 if empty.match(line): continue
2440 par = get_par(line, 2, 2, fn=fn, lineno=lineno)
2441 if not par: continue
2442 self.add_item('MODULE', par[0], proto=par[1], fn=fn, lineno=lineno)
2443 elif ctx == 'IMPORT_TAG':
2444 if empty.match(line): continue
2445 par = get_par(line, 3, 3, fn=fn, lineno=lineno)
2446 if not par: continue
2447 self.add_item(ctx, par[0], ttag=(par[1], par[2]), fn=fn, lineno=lineno)
2448 elif ctx == 'OMIT_ASSIGNMENT':
2449 if empty.match(line): continue
2450 par = get_par(line, 1, 1, fn=fn, lineno=lineno)
2451 if not par: continue
2452 self.add_item(ctx, par[0], omit=True, fn=fn, lineno=lineno)
2453 elif ctx == 'NO_OMIT_ASSGN':
2454 if empty.match(line): continue
2455 par = get_par(line, 1, 1, fn=fn, lineno=lineno)
2456 if not par: continue
2457 self.add_item(ctx, par[0], omit=False, fn=fn, lineno=lineno)
2458 elif ctx == 'VIRTUAL_ASSGN':
2459 if empty.match(line): continue
2460 par = get_par(line, 2, -1, fn=fn, lineno=lineno)
2461 if not par: continue
2462 if (len(par[1].split('/')) > 1) and not self.check_item('SET_TYPE', par[1]):
2463 self.add_item('SET_TYPE', par[1], type=par[0], fn=fn, lineno=lineno)
2464 self.add_item('VIRTUAL_ASSGN', par[1], name=par[0], fn=fn, lineno=lineno)
2466 self.add_item('SET_TYPE', nm, type=par[0], fn=fn, lineno=lineno)
2467 if not par[0][0].isupper():
2468 warnings.warn_explicit("Virtual assignment should have uppercase name (%s)" % (par[0]),
2469 UserWarning, fn, lineno)
2470 elif ctx == 'SET_TYPE':
2471 if empty.match(line): continue
2472 par = get_par(line, 2, 2, fn=fn, lineno=lineno)
2473 if not par: continue
2474 if not self.check_item('VIRTUAL_ASSGN', par[0]):
2475 self.add_item('SET_TYPE', par[0], type=par[1], fn=fn, lineno=lineno)
2476 if not par[1][0].isupper():
2477 warnings.warn_explicit("Set type should have uppercase name (%s)" % (par[1]),
2478 UserWarning, fn, lineno)
2479 elif ctx == 'TYPE_RENAME':
2480 if empty.match(line): continue
2481 par = get_par(line, 2, 2, fn=fn, lineno=lineno)
2482 if not par: continue
2483 self.add_item('TYPE_RENAME', par[0], eth_name=par[1], fn=fn, lineno=lineno)
2484 if not par[1][0].isupper():
2485 warnings.warn_explicit("Type should be renamed to uppercase name (%s)" % (par[1]),
2486 UserWarning, fn, lineno)
2487 elif ctx == 'FIELD_RENAME':
2488 if empty.match(line): continue
2489 par = get_par(line, 2, 2, fn=fn, lineno=lineno)
2490 if not par: continue
2491 self.add_item('FIELD_RENAME', par[0], eth_name=par[1], fn=fn, lineno=lineno)
2492 if not par[1][0].islower():
2493 warnings.warn_explicit("Field should be renamed to lowercase name (%s)" % (par[1]),
2494 UserWarning, fn, lineno)
2495 elif ctx == 'TF_RENAME':
2496 if empty.match(line): continue
2497 par = get_par(line, 2, 2, fn=fn, lineno=lineno)
2498 if not par: continue
2499 tmpu = par[1][0].upper() + par[1][1:]
2500 tmpl = par[1][0].lower() + par[1][1:]
2501 self.add_item('TYPE_RENAME', par[0], eth_name=tmpu, fn=fn, lineno=lineno)
2502 if not tmpu[0].isupper():
2503 warnings.warn_explicit("Type should be renamed to uppercase name (%s)" % (par[1]),
2504 UserWarning, fn, lineno)
2505 self.add_item('FIELD_RENAME', par[0], eth_name=tmpl, fn=fn, lineno=lineno)
2506 if not tmpl[0].islower():
2507 warnings.warn_explicit("Field should be renamed to lowercase name (%s)" % (par[1]),
2508 UserWarning, fn, lineno)
2509 elif ctx in ('TYPE_ATTR', 'ETYPE_ATTR', 'FIELD_ATTR', 'EFIELD_ATTR'):
2510 if empty.match(line): continue
2511 par = get_par_nm(line, 1, 1, fn=fn, lineno=lineno)
2512 if not par: continue
2513 self.add_item(ctx, par[0], attr=par[1], fn=fn, lineno=lineno)
2514 elif ctx == 'FN_PARS':
2515 if empty.match(line): continue
2517 par = get_par_nm(line, 0, 0, fn=fn, lineno=lineno)
2519 par = get_par_nm(line, 1, 1, fn=fn, lineno=lineno)
2520 if not par: continue
2522 self.update_item(ctx, name, pars=par[0], fn=fn, lineno=lineno)
2524 self.add_item(ctx, par[0], pars=par[1], fn=fn, lineno=lineno)
2525 elif ctx in ('FN_HDR', 'FN_FTR', 'FN_BODY'):
2526 self.add_fn_line(name, ctx, line, fn=fn, lineno=lineno)
2527 elif ctx == 'CLASS':
2528 if empty.match(line): continue
2529 par = get_par(line, 1, 3, fn=fn, lineno=lineno)
2530 if not par: continue
2531 if not set_type_to_class(name, par[0], par[1:]):
2532 warnings.warn_explicit("Could not set type of class member %s.&%s to %s" % (name, par[0], par[1]),
2533 UserWarning, fn, lineno)
2534 elif ctx == 'TABLE':
2535 self.report[name][-1]['text'] += line
2537 def set_opt(self, opt, par, fn, lineno):
2538 #print "set_opt: %s, %s" % (opt, par)
2540 par = self.check_par(par, 1, 1, fn, lineno)
2542 self.include_path.append(par[0])
2543 elif opt in ("-b", "BER", "CER", "DER"):
2544 par = self.check_par(par, 0, 0, fn, lineno)
2545 self.ectx.encoding = 'ber'
2546 elif opt in ("-X", "NEW_BER"):
2547 par = self.check_par(par, 0, 0, fn, lineno)
2548 self.ectx.new_ber = True
2549 elif opt in ("PER",):
2550 par = self.check_par(par, 0, 0, fn, lineno)
2551 self.ectx.encoding = 'per'
2552 elif opt in ("-p", "PROTO"):
2553 par = self.check_par(par, 1, 1, fn, lineno)
2555 self.ectx.proto_opt = par[0]
2556 self.ectx.merge_modules = True
2557 elif opt in ("-F", "CREATE_FIELDS"):
2558 par = self.check_par(par, 0, 1, fn, lineno)
2560 if (len(par) > 0): tnm = par[0]
2561 self.ectx.fld_opt[tnm] = True
2562 elif opt in ("-T",):
2563 par = self.check_par(par, 0, 0, fn, lineno)
2564 self.ectx.tag_opt = True
2565 elif opt in ("ALIGNED",):
2566 par = self.check_par(par, 0, 0, fn, lineno)
2567 self.ectx.aligned = True
2568 elif opt in ("-u", "UNALIGNED"):
2569 par = self.check_par(par, 0, 0, fn, lineno)
2570 self.ectx.aligned = False
2571 elif opt in ("-d",):
2572 par = self.check_par(par, 1, 1, fn, lineno)
2574 self.ectx.dbgopt = par[0]
2575 elif opt in ("-e",):
2576 par = self.check_par(par, 0, 0, fn, lineno)
2577 self.ectx.expcnf = True
2578 elif opt in ("-S",):
2579 par = self.check_par(par, 0, 0, fn, lineno)
2580 self.ectx.merge_modules = True
2581 elif opt in ("GROUP_BY_PROT",):
2582 par = self.check_par(par, 0, 0, fn, lineno)
2583 self.ectx.group_by_prot = True
2584 elif opt in ("-o",):
2585 par = self.check_par(par, 1, 1, fn, lineno)
2587 self.ectx.outnm_opt = par[0]
2588 elif opt in ("-O",):
2589 par = self.check_par(par, 1, 1, fn, lineno)
2591 self.ectx.output.outdir = par[0]
2592 elif opt in ("-s",):
2593 par = self.check_par(par, 1, 1, fn, lineno)
2595 self.ectx.output.single_file = par[0]
2596 elif opt in ("-k",):
2597 par = self.check_par(par, 0, 0, fn, lineno)
2598 self.ectx.output.keep = True
2599 elif opt in ("-L",):
2600 par = self.check_par(par, 0, 0, fn, lineno)
2601 self.suppress_line = True
2602 elif opt in ("EMBEDDED_PDV_CB",):
2603 par = self.check_par(par, 1, 1, fn, lineno)
2605 self.ectx.default_embedded_pdv_cb = par[0]
2606 elif opt in ("EXTERNAL_TYPE_CB",):
2607 par = self.check_par(par, 1, 1, fn, lineno)
2609 self.ectx.default_external_type_cb = par[0]
2611 warnings.warn_explicit("Unknown option %s" % (opt),
2612 UserWarning, fn, lineno)
2614 def dbg_print(self):
2615 print "\n# Conformance values"
2616 print "%-15s %-4s %-15s %-20s %s" % ("File", "Line", "Table", "Key", "Value")
2618 tbls = self.table.keys()
2621 keys = self.table[t].keys()
2624 print "%-15s %4s %-15s %-20s %s" % (
2625 self.table[t][k]['fn'], self.table[t][k]['lineno'], t, k, str(self.table[t][k][self.tblcfg[t]['val_nm']]))
2627 def unused_report(self):
2628 tbls = self.table.keys()
2631 if not self.tblcfg[t]['chk_use']: continue
2632 keys = self.table[t].keys()
2635 if not self.table[t][k]['used']:
2636 warnings.warn_explicit("Unused %s for %s" % (t, k),
2637 UserWarning, self.table[t][k]['fn'], self.table[t][k]['lineno'])
2638 fnms = self.fn.keys()
2641 keys = self.fn[f].keys()
2644 if not self.fn[f][k]: continue
2645 if not self.fn[f][k]['used']:
2646 warnings.warn_explicit("Unused %s for %s" % (k, f),
2647 UserWarning, self.fn[f][k]['fn'], self.fn[f][k]['lineno'])
2649 #--- EthOut -------------------------------------------------------------------
2655 self.single_file = None
2656 self.created_files = {}
2657 self.created_files_ord = []
2660 def outcomment(self, ln, comment=None):
2662 return '%s %s\n' % (comment, ln)
2664 return '/* %-74s */\n' % (ln)
2666 def created_file_add(self, name, keep_anyway):
2667 name = os.path.normcase(os.path.abspath(name))
2668 if not self.created_files.has_key(name):
2669 self.created_files_ord.append(name)
2670 self.created_files[name] = keep_anyway
2672 self.created_files[name] = self.created_files[name] or keep_anyway
2674 def created_file_exists(self, name):
2675 name = os.path.normcase(os.path.abspath(name))
2676 return self.created_files.has_key(name)
2678 #--- output_fname -------------------------------------------------------
2679 def output_fname(self, ftype, ext='c'):
2681 if not ext in ('cnf',):
2688 #--- output_fullname -------------------------------------------------------
2689 def output_fullname(self, ftype, ext='c'):
2690 return os.path.join(self.outdir, self.output_fname(ftype, ext=ext))
2691 #--- file_open -------------------------------------------------------
2692 def file_open(self, ftype, ext='c'):
2693 fn = self.output_fullname(ftype, ext=ext)
2694 if self.created_file_exists(fn):
2701 fx.write(self.fhdr(fn, comment = comment))
2703 if (not self.single_file and not self.created_file_exists(fn)):
2704 fx.write(self.fhdr(fn))
2705 if not self.ectx.merge_modules:
2708 if self.ectx.groups():
2710 if (len(self.ectx.modules) > 1):
2712 for (m, p) in self.ectx.modules:
2715 mstr += "Module %s" % (self.ectx.Module())
2716 mstr += " --- --- ---"
2717 fx.write(self.outcomment(mstr, comment))
2720 #--- file_close -------------------------------------------------------
2721 def file_close(self, fx, discard=False, keep_anyway=False):
2723 if discard and not self.created_file_exists(fx.name):
2726 self.created_file_add(fx.name, keep_anyway)
2727 #--- fhdr -------------------------------------------------------
2728 def fhdr(self, fn, comment=None):
2730 out += self.outcomment('Do not modify this file.', comment)
2731 out += self.outcomment('It is created automatically by the ASN.1 to Wireshark dissector compiler', comment)
2732 out += self.outcomment(fn, comment)
2733 out += self.outcomment(' '.join(sys.argv), comment)
2737 #--- dbg_print -------------------------------------------------------
2738 def dbg_print(self):
2739 print "\n# Output files"
2740 print "\n".join(self.created_files_ord)
2743 #--- make_single_file -------------------------------------------------------
2744 def make_single_file(self):
2745 if (not self.single_file): return
2746 in_nm = self.single_file + '.c'
2747 out_nm = self.output_fullname('')
2748 self.do_include(out_nm, in_nm)
2749 in_nm = self.single_file + '.h'
2750 if (os.path.exists(in_nm)):
2751 out_nm = self.output_fullname('', ext='h')
2752 self.do_include(out_nm, in_nm)
2754 for fn in self.created_files_ord:
2755 if not self.created_files[fn]:
2758 #--- do_include -------------------------------------------------------
2759 def do_include(self, out_nm, in_nm):
2760 def check_file(fn, fnlist):
2761 fnfull = os.path.normcase(os.path.abspath(fn))
2762 if (fnlist.has_key(fnfull) and os.path.exists(fnfull)):
2763 return os.path.normpath(fn)
2765 fin = file(in_nm, "r")
2766 fout = file(out_nm, "w")
2767 fout.write(self.fhdr(out_nm))
2768 fout.write('/* Input file: ' + in_nm +' */\n')
2770 fout.write('#line 1 "%s"\n' % (in_nm))
2772 include = re.compile(r'^\s*#\s*include\s+[<"](?P<fname>[^>"]+)[>"]', re.IGNORECASE)
2777 cont_linenum = cont_linenum + 1;
2778 line = fin.readline()
2779 if (line == ''): break
2781 result = include.search(line)
2782 #if (result): print os.path.normcase(os.path.abspath(result.group('fname')))
2784 ifile = check_file(os.path.join(os.path.split(in_nm)[0], result.group('fname')), self.created_files)
2786 ifile = check_file(os.path.join(self.outdir, result.group('fname')), self.created_files)
2788 ifile = check_file(result.group('fname'), self.created_files)
2791 fout.write('/*--- Included file: ' + ifile + ' ---*/\n')
2792 fout.write('#line 1 "' + ifile + '"\n')
2793 finc = file(ifile, "r")
2794 fout.write(finc.read())
2796 fout.write('/*--- End of included file: ' + ifile + ' ---*/\n')
2797 fout.write('#line %i "%s"\n' % (cont_linenum+1,in_nm) )
2806 #--- Node ---------------------------------------------------------------------
2808 def __init__(self,*args, **kw):
2810 self.type = self.__class__.__name__
2812 assert (len(args) == 1)
2814 self.__dict__.update (kw)
2815 def str_child (self, key, child, depth):
2816 indent = " " * (2 * depth)
2817 keystr = indent + key + ": "
2818 if key == 'type': # already processed in str_depth
2820 if isinstance (child, Node): # ugh
2821 return keystr + "\n" + child.str_depth (depth+1)
2822 if type (child) == type ([]):
2825 if isinstance (x, Node):
2826 l.append (x.str_depth (depth+1))
2828 l.append (indent + " " + str(x) + "\n")
2829 return keystr + "[\n" + ''.join(l) + indent + "]\n"
2831 return keystr + str (child) + "\n"
2832 def str_depth (self, depth): # ugh
2833 indent = " " * (2 * depth)
2834 l = ["%s%s" % (indent, self.type)]
2835 l.append ("".join (map (lambda (k,v): self.str_child (k, v, depth + 1),
2836 self.__dict__.items ())))
2837 return "\n".join (l)
2839 return "\n" + self.str_depth (0)
2840 def to_python (self, ctx):
2841 return self.str_depth (ctx.indent_lev)
2843 def eth_reg(self, ident, ectx):
2846 def fld_obj_repr(self, ectx):
2847 return "/* TO DO %s */" % (str(self))
2849 #--- ValueAssignment -------------------------------------------------------------
2850 class ValueAssignment (Node):
2851 def __init__(self,*args, **kw) :
2852 Node.__init__ (self,*args, **kw)
2854 def eth_reg(self, ident, ectx):
2855 if ectx.conform.omit_assignment('V', self.ident, ectx.Module()): return # Assignment to omit
2856 ectx.eth_reg_vassign(self)
2857 ectx.eth_reg_value(self.ident, self.typ, self.val)
2859 #--- ObjectAssignment -------------------------------------------------------------
2860 class ObjectAssignment (Node):
2861 def __init__(self,*args, **kw) :
2862 Node.__init__ (self,*args, **kw)
2864 def __eq__(self, other):
2865 if self.cls != other.cls:
2867 if len(self.val) != len(other.val):
2869 for f in (self.val.keys()):
2870 if not other.val.has_key(f):
2872 if isinstance(self.val[f], Node) and isinstance(other.val[f], Node):
2873 if not self.val[f].fld_obj_eq(other.val[f]):
2876 if str(self.val[f]) != str(other.val[f]):
2880 def eth_reg(self, ident, ectx):
2881 def make_virtual_type(cls, field, prefix):
2882 if isinstance(self.val, str): return
2883 if self.val.has_key(field) and not isinstance(self.val[field], Type_Ref):
2884 vnm = prefix + '-' + self.ident
2885 virtual_tr = Type_Ref(val = vnm)
2887 self.val[field] = virtual_tr
2888 ectx.eth_reg_assign(vnm, t, virt=True)
2889 ectx.eth_reg_type(vnm, t)
2890 t.eth_reg_sub(vnm, ectx)
2891 if self.val.has_key(field) and ectx.conform.check_item('PDU', cls + '.' + field):
2892 ectx.eth_reg_field(self.val[field].val, self.val[field].val, impl=self.val[field].HasImplicitTag(ectx), pdu=ectx.conform.use_item('PDU', cls + '.' + field))
2894 # end of make_virtual_type()
2895 if ectx.conform.omit_assignment('V', self.ident, ectx.Module()): return # Assignment to omit
2896 ectx.eth_reg_oassign(self)
2897 if (self.cls == 'TYPE-IDENTIFIER') or (self.cls == 'ABSTRACT-SYNTAX'):
2898 make_virtual_type(self.cls, '&Type', 'TYPE')
2899 if (self.cls == 'OPERATION'):
2900 make_virtual_type(self.cls, '&ArgumentType', 'ARG')
2901 make_virtual_type(self.cls, '&ResultType', 'RES')
2902 if (self.cls == 'ERROR'):
2903 make_virtual_type(self.cls, '&ParameterType', 'PAR')
2906 #--- Type ---------------------------------------------------------------------
2908 def __init__(self,*args, **kw) :
2912 self.named_list = None
2913 Node.__init__ (self,*args, **kw)
2916 if self.name is None :
2921 def HasConstraint(self):
2922 if self.constr is None :
2927 def HasSizeConstraint(self):
2928 return self.HasConstraint() and self.constr.IsSize()
2930 def HasValueConstraint(self):
2931 return self.HasConstraint() and self.constr.IsValue()
2933 def HasPermAlph(self):
2934 return self.HasConstraint() and self.constr.IsPermAlph()
2936 def HasContentsConstraint(self):
2937 return self.HasConstraint() and self.constr.IsContents()
2939 def HasOwnTag(self):
2940 return len(self.tags) > 0
2942 def HasImplicitTag(self, ectx):
2943 return (self.HasOwnTag() and self.tags[0].IsImplicit(ectx))
2945 def IndetermTag(self, ectx):
2948 def AddTag(self, tag):
2949 self.tags[0:0] = [tag]
2951 def GetTag(self, ectx):
2952 #print "GetTag(%s)\n" % self.name;
2953 if (self.HasOwnTag()):
2954 return self.tags[0].GetTag(ectx)
2956 return self.GetTTag(ectx)
2958 def GetTTag(self, ectx):
2959 print "#Unhandled GetTTag() in %s" % (self.type)
2960 print self.str_depth(1)
2961 return ('BER_CLASS_unknown', 'TAG_unknown')
2963 def SetName(self, name):
2966 def AddConstraint(self, constr):
2967 if not self.HasConstraint():
2968 self.constr = constr
2970 self.constr = Constraint(type = 'Intersection', subtype = [self.constr, constr])
2972 def eth_tname(self):
2973 return '#' + self.type + '_' + str(id(self))
2975 def eth_ftype(self, ectx):
2976 return ('FT_NONE', 'BASE_NONE')
2978 def eth_strings(self):
2981 def eth_need_tree(self):
2984 def eth_has_vals(self):
2987 def eth_has_enum(self, tname, ectx):
2988 return self.eth_has_vals() and (ectx.eth_type[tname]['enum'] & EF_ENUM)
2990 def eth_need_pdu(self, ectx):
2993 def eth_named_bits(self):
2996 def eth_reg_sub(self, ident, ectx):
2999 def get_components(self, ectx):
3000 print "#Unhandled get_components() in %s" % (self.type)
3001 print self.str_depth(1)
3004 def sel_req(self, sel, ectx):
3005 print "#Selection '%s' required for non-CHOICE type %s" % (sel, self.type)
3006 print self.str_depth(1)
3008 def fld_obj_eq(self, other):
3009 return isinstance(other, Type) and (self.eth_tname() == other.eth_tname())
3011 def eth_reg(self, ident, ectx, tstrip=0, tagflag=False, selflag=False, idx='', parent=None):
3012 #print "eth_reg(): %s, ident=%s, tstrip=%d, tagflag=%s, selflag=%s, parent=%s" %(self.type, ident, tstrip, str(tagflag), str(selflag), str(parent))
3013 if (ectx.Tag() and (len(self.tags) > tstrip)):
3014 tagged_type = TaggedType(val=self, tstrip=tstrip)
3015 tagged_type.AddTag(self.tags[tstrip])
3016 if not tagflag: # 1st tagged level
3017 if self.IsNamed() and not selflag:
3018 tagged_type.SetName(self.name)
3019 tagged_type.eth_reg(ident, ectx, tstrip=1, tagflag=tagflag, idx=idx, parent=parent)
3022 if ident and self.IsNamed() and not tagflag and not selflag:
3023 nm = ident + '/' + self.name
3026 elif self.IsNamed():
3028 if not ident and ectx.conform.omit_assignment('T', nm, ectx.Module()): return # Assignment to omit
3029 if not ident: # Assignment
3030 ectx.eth_reg_assign(nm, self)
3031 if self.type == 'Type_Ref':
3032 ectx.eth_reg_type(nm, self)
3033 virtual_tr = Type_Ref(val=ectx.conform.use_item('SET_TYPE', nm))
3034 if (self.type == 'Type_Ref') or ectx.conform.check_item('SET_TYPE', nm):
3035 if ident and (ectx.conform.check_item('TYPE_RENAME', nm) or ectx.conform.get_fn_presence(nm) or selflag):
3036 if ectx.conform.check_item('SET_TYPE', nm):
3037 ectx.eth_reg_type(nm, virtual_tr) # dummy Type Reference
3039 ectx.eth_reg_type(nm, self) # new type
3041 elif ectx.conform.check_item('SET_TYPE', nm):
3042 trnm = ectx.conform.use_item('SET_TYPE', nm)
3046 ectx.eth_reg_type(nm, self)
3048 if ectx.conform.check_item('VIRTUAL_ASSGN', nm):
3049 vnm = ectx.conform.use_item('VIRTUAL_ASSGN', nm)
3050 ectx.eth_reg_assign(vnm, self, virt=True)
3051 ectx.eth_reg_type(vnm, self)
3052 self.eth_reg_sub(vnm, ectx)
3053 if parent and (ectx.type[parent]['val'].type == 'TaggedType'):
3054 ectx.type[parent]['val'].eth_set_val_name(parent, trnm, ectx)
3055 if ident and not tagflag:
3056 ectx.eth_reg_field(nm, trnm, idx=idx, parent=parent, impl=self.HasImplicitTag(ectx))
3057 if ectx.conform.check_item('SET_TYPE', nm):
3058 virtual_tr.eth_reg_sub(nm, ectx)
3060 self.eth_reg_sub(nm, ectx)
3062 def eth_get_size_constr(self, ectx):
3063 (minv, maxv, ext) = ('MIN', 'MAX', False)
3064 if self.HasSizeConstraint():
3065 if self.constr.IsSize():
3066 (minv, maxv, ext) = self.constr.GetSize(ectx)
3067 if (self.constr.type == 'Intersection'):
3068 if self.constr.subtype[0].IsSize():
3069 (minv, maxv, ext) = self.constr.subtype[0].GetSize(ectx)
3070 elif self.constr.subtype[1].IsSize():
3071 (minv, maxv, ext) = self.constr.subtype[1].GetSize(ectx)
3072 if minv == 'MIN': minv = 'NO_BOUND'
3073 if maxv == 'MAX': maxv = 'NO_BOUND'
3074 if (ext): ext = 'TRUE'
3076 return (minv, maxv, ext)
3078 def eth_get_value_constr(self, ectx):
3079 (minv, maxv, ext) = ('MIN', 'MAX', False)
3080 if self.HasValueConstraint():
3081 (minv, maxv, ext) = self.constr.GetValue(ectx)
3082 if minv == 'MIN': minv = 'NO_BOUND'
3083 if maxv == 'MAX': maxv = 'NO_BOUND'
3084 if str(minv).isdigit(): minv += 'U'
3085 if str(maxv).isdigit(): maxv += 'U'
3086 if (ext): ext = 'TRUE'
3088 return (minv, maxv, ext)
3090 def eth_get_alphabet_constr(self, ectx):
3091 (alph, alphlen) = ('NULL', '0')
3092 if self.HasPermAlph():
3093 alph = self.constr.GetPermAlph(ectx)
3096 if (alph != 'NULL'):
3097 if (((alph[0] + alph[-1]) == '""') and (not alph.count('"', 1, -1))):
3098 alphlen = str(len(alph) - 2)
3100 alphlen = 'strlen(%s)' % (alph)
3101 return (alph, alphlen)
3103 def eth_type_vals(self, tname, ectx):
3104 if self.eth_has_vals():
3105 print "#Unhandled eth_type_vals('%s') in %s" % (tname, self.type)
3106 print self.str_depth(1)
3109 def eth_type_enum(self, tname, ectx):
3110 if self.eth_has_enum(tname, ectx):
3111 print "#Unhandled eth_type_enum('%s') in %s" % (tname, self.type)
3112 print self.str_depth(1)
3115 def eth_type_default_table(self, ectx, tname):
3118 def eth_type_default_body(self, ectx):
3119 print "#Unhandled eth_type_default_body() in %s" % (self.type)
3120 print self.str_depth(1)
3123 def eth_type_default_pars(self, ectx, tname):
3130 'OFFSET' : 'offset',
3132 'HF_INDEX' : 'hf_index',
3134 'IMPLICIT_TAG' : 'implicit_tag',
3136 if (ectx.eth_type[tname]['tree']):
3137 pars['ETT_INDEX'] = ectx.eth_type[tname]['tree']
3138 if (ectx.merge_modules):
3141 pars['PROTOP'] = ectx.eth_type[tname]['proto'] + '_'
3144 def eth_type_fn(self, proto, tname, ectx):
3145 body = self.eth_type_default_body(ectx, tname)
3146 pars = self.eth_type_default_pars(ectx, tname)
3147 if ectx.conform.check_item('FN_PARS', tname):
3148 pars.update(ectx.conform.use_item('FN_PARS', tname))
3149 elif ectx.conform.check_item('FN_PARS', ectx.eth_type[tname]['ref'][0]):
3150 pars.update(ectx.conform.use_item('FN_PARS', ectx.eth_type[tname]['ref'][0]))
3151 pars['DEFAULT_BODY'] = body
3153 for k in pars.keys():
3155 pars[k] = pars[k] % pars
3157 raise sys.exc_type, "%s\n%s" % (str(pars), sys.exc_value)
3159 out += self.eth_type_default_table(ectx, tname) % pars
3160 out += ectx.eth_type_fn_hdr(tname)
3161 out += ectx.eth_type_fn_body(tname, body, pars=pars)
3162 out += ectx.eth_type_fn_ftr(tname)
3165 #--- Value --------------------------------------------------------------------
3167 def __init__(self,*args, **kw) :
3169 Node.__init__ (self,*args, **kw)
3171 def SetName(self, name) :
3174 def to_str(self, ectx):
3175 return str(self.val)
3180 def fld_obj_repr(self, ectx):
3181 return self.to_str(ectx)
3183 #--- Value_Ref -----------------------------------------------------------------
3184 class Value_Ref (Value):
3185 def to_str(self, ectx):
3186 return asn2c(self.val)
3188 #--- ObjectClass ---------------------------------------------------------------------
3189 class ObjectClass (Node):
3190 def __init__(self,*args, **kw) :
3192 Node.__init__ (self,*args, **kw)
3194 def SetName(self, name):
3196 add_class_ident(self.name)
3198 def eth_reg(self, ident, ectx):
3199 if ectx.conform.omit_assignment('C', self.name, ectx.Module()): return # Assignment to omit
3200 ectx.eth_reg_objectclass(self.name, self)
3202 #--- Class_Ref -----------------------------------------------------------------
3203 class Class_Ref (ObjectClass):
3206 #--- ObjectClassDefn ---------------------------------------------------------------------
3207 class ObjectClassDefn (ObjectClass):
3208 def reg_types(self):
3209 for fld in self.fields:
3210 repr = fld.fld_repr()
3211 set_type_to_class(self.name, repr[0], repr[1:])
3214 #--- Tag ---------------------------------------------------------------
3216 def to_python (self, ctx):
3217 return 'asn1.TYPE(%s,%s)' % (mk_tag_str (ctx, self.tag.cls,
3220 self.typ.to_python (ctx))
3221 def IsImplicit(self, ectx):
3222 return ((self.mode == 'IMPLICIT') or ((self.mode == 'default') and (ectx.tag_def == 'IMPLICIT')))
3224 def GetTag(self, ectx):
3226 if (self.cls == 'UNIVERSAL'): tc = 'BER_CLASS_UNI'
3227 elif (self.cls == 'APPLICATION'): tc = 'BER_CLASS_APP'
3228 elif (self.cls == 'CONTEXT'): tc = 'BER_CLASS_CON'
3229 elif (self.cls == 'PRIVATE'): tc = 'BER_CLASS_PRI'
3230 return (tc, self.num)
3232 def eth_tname(self):
3234 if (self.cls == 'UNIVERSAL'): n = 'U'
3235 elif (self.cls == 'APPLICATION'): n = 'A'
3236 elif (self.cls == 'CONTEXT'): n = 'C'
3237 elif (self.cls == 'PRIVATE'): n = 'P'
3238 return n + str(self.num)
3240 #--- Constraint ---------------------------------------------------------------
3241 class Constraint (Node):
3242 def to_python (self, ctx):
3243 print "Ignoring constraint:", self.type
3244 return self.subtype.typ.to_python (ctx)
3246 return "Constraint: type=%s, subtype=%s" % (self.type, self.subtype)
3248 def eth_tname(self):
3249 return '#' + self.type + '_' + str(id(self))
3252 return (self.type == 'Size' and self.subtype.IsValue()) \
3253 or (self.type == 'Intersection' and (self.subtype[0].IsSize() or self.subtype[1].IsSize())) \
3255 def GetSize(self, ectx):
3256 (minv, maxv, ext) = ('MIN', 'MAX', False)
3258 if self.type == 'Size':
3259 (minv, maxv, ext) = self.subtype.GetValue(ectx)
3260 elif self.type == 'Intersection':
3261 if self.subtype[0].IsSize() and not self.subtype[1].IsSize():
3262 (minv, maxv, ext) = self.subtype[0].GetSize(ectx)
3263 elif not self.subtype[0].IsSize() and self.subtype[1].IsSize():
3264 (minv, maxv, ext) = self.subtype[1].GetSize(ectx)
3265 return (minv, maxv, ext)
3268 return self.type == 'SingleValue' \
3269 or self.type == 'ValueRange' \
3270 or (self.type == 'Intersection' and (self.subtype[0].IsValue() or self.subtype[1].IsValue())) \
3271 or (self.type == 'Union' and (self.subtype[0].IsValue() and self.subtype[1].IsValue()))
3273 def GetValue(self, ectx):
3274 (minv, maxv, ext) = ('MIN', 'MAX', False)
3276 if self.type == 'SingleValue':
3277 minv = ectx.value_get_eth(self.subtype)
3278 maxv = ectx.value_get_eth(self.subtype)
3279 ext = hasattr(self, 'ext') and self.ext
3280 elif self.type == 'ValueRange':
3281 minv = ectx.value_get_eth(self.subtype[0])
3282 maxv = ectx.value_get_eth(self.subtype[1])
3283 ext = hasattr(self, 'ext') and self.ext
3284 elif self.type == 'Intersection':
3285 if self.subtype[0].IsValue() and not self.subtype[1].IsValue():
3286 (minv, maxv, ext) = self.subtype[0].GetValue(ectx)
3287 elif not self.subtype[0].IsValue() and self.subtype[1].IsValue():
3288 (minv, maxv, ext) = self.subtype[1].GetValue(ectx)
3289 elif self.subtype[0].IsValue() and self.subtype[1].IsValue():
3290 v0 = self.subtype[0].GetValue(ectx)
3291 v1 = self.subtype[1].GetValue(ectx)
3292 (minv, maxv, ext) = (ectx.value_max(v0[0],v1[0]), ectx.value_min(v0[1],v1[1]), v0[2] and v1[2])
3293 elif self.type == 'Union':
3294 if self.subtype[0].IsValue() and self.subtype[1].IsValue():
3295 v0 = self.subtype[0].GetValue(ectx)
3296 v1 = self.subtype[1].GetValue(ectx)
3297 (minv, maxv, ext) = (ectx.value_min(v0[0],v1[0]), ectx.value_max(v0[1],v1[1]), v0[2] or v1[2])
3298 return (minv, maxv, ext)
3300 def IsAlphabet(self):
3301 return self.type == 'SingleValue' \
3302 or self.type == 'ValueRange' \
3303 or (self.type == 'Intersection' and (self.subtype[0].IsAlphabet() or self.subtype[1].IsAlphabet())) \
3304 or (self.type == 'Union' and (self.subtype[0].IsAlphabet() and self.subtype[1].IsAlphabet()))
3306 def GetAlphabet(self, ectx):
3308 if self.IsAlphabet():
3309 if self.type == 'SingleValue':
3310 alph = ectx.value_get_eth(self.subtype)
3311 elif self.type == 'ValueRange':
3312 if ((len(self.subtype[0]) == 3) and ((self.subtype[0][0] + self.subtype[0][-1]) == '""') \
3313 and (len(self.subtype[1]) == 3) and ((self.subtype[1][0] + self.subtype[1][-1]) == '""')):
3315 for c in range(ord(self.subtype[0][1]), ord(self.subtype[1][1]) + 1):
3318 elif self.type == 'Union':
3319 if self.subtype[0].IsAlphabet() and self.subtype[1].IsAlphabet():
3320 a0 = self.subtype[0].GetAlphabet(ectx)
3321 a1 = self.subtype[1].GetAlphabet(ectx)
3322 if (((a0[0] + a0[-1]) == '""') and not a0.count('"', 1, -1) \
3323 and ((a1[0] + a1[-1]) == '""') and not a1.count('"', 1, -1)):
3324 alph = '"' + a0[1:-1] + a1[1:-1] + '"'
3326 alph = a0 + ' ' + a1
3329 def IsPermAlph(self):
3330 return self.type == 'From' and self.subtype.IsAlphabet() \
3331 or (self.type == 'Intersection' and (self.subtype[0].IsPermAlph() or self.subtype[1].IsPermAlph())) \
3333 def GetPermAlph(self, ectx):
3335 if self.IsPermAlph():
3336 if self.type == 'From':
3337 alph = self.subtype.GetAlphabet(ectx)
3338 elif self.type == 'Intersection':
3339 if self.subtype[0].IsPermAlph() and not self.subtype[1].IsPermAlph():
3340 alph = self.subtype[0].GetPermAlph(ectx)
3341 elif not self.subtype[0].IsPermAlph() and self.subtype[1].IsPermAlph():
3342 alph = self.subtype[1].GetPermAlph(ectx)
3345 def IsContents(self):
3346 return self.type == 'Contents' \
3347 or (self.type == 'Intersection' and (self.subtype[0].IsContents() or self.subtype[1].IsContents())) \
3349 def GetContents(self, ectx):
3351 if self.IsContents():
3352 if self.type == 'Contents':
3353 if self.subtype.type == 'Type_Ref':
3354 contents = self.subtype.val
3355 elif self.type == 'Intersection':
3356 if self.subtype[0].IsContents() and not self.subtype[1].IsContents():
3357 contents = self.subtype[0].GetContents(ectx)
3358 elif not self.subtype[0].IsContents() and self.subtype[1].IsContents():
3359 contents = self.subtype[1].GetContents(ectx)
3362 def IsNegativ(self):
3364 return isinstance(sval, str) and (sval[0] == '-')
3365 if self.type == 'SingleValue':
3366 return is_neg(self.subtype)
3367 elif self.type == 'ValueRange':
3368 if self.subtype[0] == 'MIN': return True
3369 return is_neg(self.subtype[0])
3372 def eth_constrname(self):
3374 if isinstance(val, Value_Ref):
3375 return asn2c(val.val)
3378 return 'M' + str(-int(val))
3381 except (ValueError, TypeError):
3382 return asn2c(str(val))
3385 if hasattr(self, 'ext') and self.ext:
3387 if self.type == 'SingleValue':
3388 return int2str(self.subtype) + ext
3389 elif self.type == 'ValueRange':
3390 return int2str(self.subtype[0]) + '_' + int2str(self.subtype[1]) + ext
3391 elif self.type == 'Size':
3392 return 'SIZE_' + self.subtype.eth_constrname() + ext
3394 return 'CONSTR' + str(id(self)) + ext
3397 class Module (Node):
3398 def to_python (self, ctx):
3399 ctx.tag_def = self.tag_def.dfl_tag
3401 %s""" % (self.ident, self.body.to_python (ctx))
3404 return self.ident.val
3406 def get_proto(self, ectx):
3410 prot = ectx.conform.use_item('MODULE', self.get_name(), val_dflt=self.get_name())
3413 def to_eth(self, ectx):
3414 ectx.tags_def = 'EXPLICIT' # default = explicit
3415 ectx.proto = self.get_proto(ectx)
3416 ectx.tag_def = self.tag_def.dfl_tag
3417 ectx.eth_reg_module(self)
3418 self.body.to_eth(ectx)
3420 class Module_Body (Node):
3421 def to_python (self, ctx):
3422 # XXX handle exports, imports.
3423 l = map (lambda x: x.to_python (ctx), self.assign_list)
3424 l = [a for a in l if a <> '']
3425 return "\n".join (l)
3427 def to_eth(self, ectx):
3429 ectx.eth_exports(self.exports)
3431 for i in self.imports:
3433 proto = ectx.conform.use_item('MODULE', mod, val_dflt=mod)
3434 ectx.eth_module_dep_add(ectx.Module(), mod)
3435 for s in i.symbol_list:
3436 if isinstance(s, Type_Ref):
3437 ectx.eth_import_type(s.val, mod, proto)
3438 elif isinstance(s, Value_Ref):
3439 ectx.eth_import_value(s.val, mod, proto)
3440 elif isinstance(s, Class_Ref):
3441 ectx.eth_import_class(s.val, mod, proto)
3443 msg = 'Unknown kind of imported symbol %s from %s' % (str(s), mod)
3444 warnings.warn_explicit(msg, UserWarning, '', '')
3446 for a in self.assign_list:
3449 class Default_Tags (Node):
3450 def to_python (self, ctx): # not to be used directly
3453 # XXX should just calculate dependencies as we go along.
3454 def calc_dependencies (node, dict, trace = 0):
3455 if not hasattr (node, '__dict__'):
3456 if trace: print "#returning, node=", node
3458 if isinstance (node, Type_Ref):
3460 if trace: print "#Setting", node.val
3462 for (a, val) in node.__dict__.items ():
3463 if trace: print "# Testing node ", node, "attr", a, " val", val
3466 elif isinstance (val, Node):
3467 calc_dependencies (val, dict, trace)
3468 elif isinstance (val, type ([])):
3470 calc_dependencies (v, dict, trace)
3473 class Type_Assign (Node):
3474 def __init__ (self, *args, **kw):
3475 Node.__init__ (self, *args, **kw)
3476 if isinstance (self.val, Tag): # XXX replace with generalized get_typ_ignoring_tag (no-op for Node, override in Tag)
3477 to_test = self.val.typ
3480 if isinstance (to_test, SequenceType):
3481 to_test.sequence_name = self.name.name
3483 def to_python (self, ctx):
3485 calc_dependencies (self.val, dep_dict, 0)
3486 depend_list = dep_dict.keys ()
3487 return ctx.register_assignment (self.name.name,
3488 self.val.to_python (ctx),
3491 class PyQuote (Node):
3492 def to_python (self, ctx):
3493 return ctx.register_pyquote (self.val)
3495 #--- Type_Ref -----------------------------------------------------------------
3496 class Type_Ref (Type):
3497 def to_python (self, ctx):
3500 def eth_reg_sub(self, ident, ectx):
3501 ectx.eth_dep_add(ident, self.val)
3503 def eth_tname(self):
3504 return asn2c(self.val)
3506 def fld_obj_repr(self, ectx):
3509 def get_components(self, ectx):
3510 if not ectx.type.has_key(self.val) or ectx.type[self.val]['import']:
3511 msg = "Can not get COMPONENTS OF %s which is imported type" % (self.val)
3512 warnings.warn_explicit(msg, UserWarning, '', '')
3515 return ectx.type[self.val]['val'].get_components(ectx)
3517 def GetTTag(self, ectx):
3518 #print "GetTTag(%s)\n" % self.val;
3519 if (ectx.type[self.val]['import']):
3520 if not ectx.type[self.val].has_key('ttag'):
3521 ttag = ectx.get_ttag_from_all(self.val, ectx.type[self.val]['import'])
3522 if not ttag and not ectx.conform.check_item('IMPORT_TAG', self.val):
3523 msg = 'Missing tag information for imported type %s from %s (%s)' % (self.val, ectx.type[self.val]['import'], ectx.type[self.val]['proto'])
3524 warnings.warn_explicit(msg, UserWarning, '', '')
3525 ttag = ('-1 /*imported*/', '-1 /*imported*/')
3526 ectx.type[self.val]['ttag'] = ectx.conform.use_item('IMPORT_TAG', self.val, val_dflt=ttag)
3527 return ectx.type[self.val]['ttag']
3529 return ectx.type[self.val]['val'].GetTag(ectx)
3531 def IndetermTag(self, ectx):
3532 if (ectx.type[self.val]['import']):
3535 return ectx.type[self.val]['val'].IndetermTag(ectx)
3537 def eth_type_default_pars(self, ectx, tname):
3539 pars = Type.eth_type_default_pars(self, ectx, tname)
3542 t = ectx.type[self.val]['ethname']
3543 pars['TYPE_REF_PROTO'] = ectx.eth_type[t]['proto']
3544 pars['TYPE_REF_TNAME'] = t
3545 pars['TYPE_REF_FN'] = 'dissect_%(TYPE_REF_PROTO)s_%(TYPE_REF_TNAME)s'
3548 def eth_type_default_body(self, ectx, tname):
3550 body = ectx.eth_fn_call('%(TYPE_REF_FN)s', ret='offset',
3551 par=(('%(IMPLICIT_TAG)s', '%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),))
3553 body = ectx.eth_fn_call('%(TYPE_REF_FN)s', ret='offset',
3554 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),))
3556 body = '#error Can not decode %s' % (tname)
3559 #--- SelectionType ------------------------------------------------------------
3560 class SelectionType (Type):
3561 def to_python (self, ctx):
3564 def sel_of_typeref(self):
3565 return self.typ.type == 'Type_Ref'
3567 def eth_reg_sub(self, ident, ectx):
3568 if not self.sel_of_typeref():
3571 self.seltype = ectx.eth_sel_req(self.typ.val, self.sel)
3572 ectx.eth_dep_add(ident, self.seltype)
3574 def eth_ftype(self, ectx):
3575 (ftype, display) = ('FT_NONE', 'BASE_NONE')
3576 if self.sel_of_typeref() and not ectx.type[self.seltype]['import']:
3577 (ftype, display) = ectx.type[self.typ.val]['val'].eth_ftype_sel(self.sel, ectx)
3578 return (ftype, display)
3580 def GetTTag(self, ectx):
3581 #print "GetTTag(%s)\n" % self.seltype;
3582 if (ectx.type[self.seltype]['import']):
3583 if not ectx.type[self.seltype].has_key('ttag'):
3584 if not ectx.conform.check_item('IMPORT_TAG', self.seltype):
3585 msg = 'Missing tag information for imported type %s from %s (%s)' % (self.seltype, ectx.type[self.seltype]['import'], ectx.type[self.seltype]['proto'])
3586 warnings.warn_explicit(msg, UserWarning, '', '')
3587 ectx.type[self.seltype]['ttag'] = ectx.conform.use_item('IMPORT_TAG', self.seltype, val_dflt=('-1 /*imported*/', '-1 /*imported*/'))
3588 return ectx.type[self.seltype]['ttag']
3590 return ectx.type[self.typ.val]['val'].GetTTagSel(self.sel, ectx)
3592 def eth_type_default_pars(self, ectx, tname):
3593 pars = Type.eth_type_default_pars(self, ectx, tname)
3594 if self.sel_of_typeref():
3595 t = ectx.type[self.seltype]['ethname']
3596 pars['TYPE_REF_PROTO'] = ectx.eth_type[t]['proto']
3597 pars['TYPE_REF_TNAME'] = t
3598 pars['TYPE_REF_FN'] = 'dissect_%(TYPE_REF_PROTO)s_%(TYPE_REF_TNAME)s'
3601 def eth_type_default_body(self, ectx, tname):
3602 if not self.sel_of_typeref():
3603 body = '#error Can not decode %s' % (tname)
3605 body = ectx.eth_fn_call('%(TYPE_REF_FN)s', ret='offset',
3606 par=(('%(IMPLICIT_TAG)s', '%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),))
3608 body = ectx.eth_fn_call('%(TYPE_REF_FN)s', ret='offset',
3609 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),))
3611 body = '#error Can not decode %s' % (tname)
3614 #--- TaggedType -----------------------------------------------------------------
3615 class TaggedType (Type):
3616 def eth_tname(self):
3618 for i in range(self.tstrip, len(self.val.tags)):
3619 tn += self.val.tags[i].eth_tname()
3621 tn += self.val.eth_tname()
3624 def eth_set_val_name(self, ident, val_name, ectx):
3625 #print "TaggedType::eth_set_val_name(): ident=%s, val_name=%s" % (ident, val_name)
3626 self.val_name = val_name
3627 ectx.eth_dep_add(ident, self.val_name)
3629 def eth_reg_sub(self, ident, ectx):
3630 self.val_name = ident + '/' + '_untag'
3631 self.val.eth_reg(self.val_name, ectx, tstrip=self.tstrip+1, tagflag=True, parent=ident)
3633 def GetTTag(self, ectx):
3634 #print "GetTTag(%s)\n" % self.seltype;
3635 return self.GetTag(ectx)
3637 def eth_ftype(self, ectx):
3638 return self.val.eth_ftype(ectx)
3640 def eth_type_default_pars(self, ectx, tname):
3641 pars = Type.eth_type_default_pars(self, ectx, tname)
3642 t = ectx.type[self.val_name]['ethname']
3643 pars['TYPE_REF_PROTO'] = ectx.eth_type[t]['proto']
3644 pars['TYPE_REF_TNAME'] = t
3645 pars['TYPE_REF_FN'] = 'dissect_%(TYPE_REF_PROTO)s_%(TYPE_REF_TNAME)s'
3646 (pars['TAG_CLS'], pars['TAG_TAG']) = self.GetTag(ectx)
3647 if self.HasImplicitTag(ectx):
3648 pars['TAG_IMPL'] = 'TRUE'
3650 pars['TAG_IMPL'] = 'FALSE'
3653 def eth_type_default_body(self, ectx, tname):
3655 body = ectx.eth_fn_call('dissect_%(ER)s_tagged_type', ret='offset',
3656 par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'),
3657 ('%(HF_INDEX)s', '%(TAG_CLS)s', '%(TAG_TAG)s', '%(TAG_IMPL)s', '%(TYPE_REF_FN)s',),))
3659 body = '#error Can not decode %s' % (tname)
3662 #--- SqType -----------------------------------------------------------
3663 class SqType (Type):
3664 def out_item(self, f, val, optional, ext, ectx):
3665 ef = ectx.field[f]['ethname']
3666 t = ectx.eth_hf[ef]['ethtype']
3668 if (ectx.Ber() and ectx.field[f]['impl']):
3671 #print "optional=%s, e.val.HasOwnTag()=%s, e.val.IndetermTag()=%s" % (str(e.optional), str(e.val.HasOwnTag()), str(e.val.IndetermTag(ectx)))
3672 #print val.str_depth(1)
3675 opt = 'BER_FLAGS_OPTIONAL'
3676 if (not val.HasOwnTag()):
3677 if (opt): opt += '|'
3678 opt += 'BER_FLAGS_NOOWNTAG'
3679 elif (val.HasImplicitTag(ectx)):
3680 if (opt): opt += '|'
3681 opt += 'BER_FLAGS_IMPLTAG'
3682 if (val.IndetermTag(ectx)):
3683 if (opt): opt += '|'
3684 opt += 'BER_FLAGS_NOTCHKTAG'
3685 if (not opt): opt = '0'
3688 opt = 'ASN1_OPTIONAL'
3690 opt = 'ASN1_NOT_OPTIONAL'
3692 (tc, tn) = val.GetTag(ectx)
3694 out = ' { %-24s, %-13s, %s, %s, dissect_%s_%s },\n' \
3695 % ('&'+ectx.eth_hf[ef]['fullname'], tc, tn, opt, ectx.eth_type[t]['proto'], t)
3697 out = ' { %-13s, %s, %s, dissect_%s },\n' \
3698 % (tc, tn, opt, efd)
3700 out = ' { %-24s, %-23s, %-17s, dissect_%s_%s },\n' \
3701 % ('&'+ectx.eth_hf[ef]['fullname'], ext, opt, ectx.eth_type[t]['proto'], t)
3706 #--- SeqType -----------------------------------------------------------
3707 class SeqType (SqType):
3709 def need_components(self):
3710 lst = self.elt_list[:]
3711 if hasattr(self, 'ext_list'):
3712 lst.extend(self.ext_list)
3713 if hasattr(self, 'elt_list2'):
3714 lst.extend(self.elt_list2)
3716 if e.type == 'components_of':
3720 def expand_components(self, ectx):
3721 while self.need_components():
3722 for i in range(len(self.elt_list)):
3723 if self.elt_list[i].type == 'components_of':
3724 comp = self.elt_list[i].typ.get_components(ectx)
3725 self.elt_list[i:i+1] = comp
3727 if hasattr(self, 'ext_list'):
3728 for i in range(len(self.ext_list)):
3729 if self.ext_list[i].type == 'components_of':
3730 comp = self.ext_list[i].typ.get_components(ectx)
3731 self.ext_list[i:i+1] = comp
3733 if hasattr(self, 'elt_list2'):
3734 for i in range(len(self.elt_list2)):
3735 if self.elt_list2[i].type == 'components_of':
3736 comp = self.elt_list2[i].typ.get_components(ectx)
3737 self.elt_list2[i:i+1] = comp
3740 def get_components(self, ectx):
3741 lst = self.elt_list[:]
3742 if hasattr(self, 'elt_list2'):
3743 lst.extend(self.elt_list2)
3746 def eth_type_default_table(self, ectx, tname):
3747 #print "eth_type_default_table(tname='%s')" % (tname)
3748 fname = ectx.eth_type[tname]['ref'][0]
3751 table = "static const %(ER)s_sequence_t %(TABLE)s[] = {\n"
3753 table = "static const %(ER)s_old_sequence_t %(TABLE)s[] = {\n"
3755 table = "static const %(ER)s_sequence_t %(TABLE)s[] = {\n"
3756 if hasattr(self, 'ext_list'):
3757 ext = 'ASN1_EXTENSION_ROOT'
3759 ext = 'ASN1_NO_EXTENSIONS'
3760 for e in (self.elt_list):
3761 f = fname + '/' + e.val.name
3762 table += self.out_item(f, e.val, e.optional, ext, ectx)
3763 if hasattr(self, 'ext_list'):
3764 for e in (self.ext_list):
3765 f = fname + '/' + e.val.name
3766 table += self.out_item(f, e.val, e.optional, 'ASN1_NOT_EXTENSION_ROOT', ectx)
3767 if hasattr(self, 'elt_list2'):
3768 for e in (self.elt_list2):
3769 f = fname + '/' + e.val.name
3770 table += self.out_item(f, e.val, e.optional, ext, ectx)
3773 table += " { NULL, 0, 0, 0, NULL }\n};\n"
3775 table += " { 0, 0, 0, NULL }\n};\n"
3777 table += " { NULL, 0, 0, NULL }\n};\n"
3780 #--- SeqOfType -----------------------------------------------------------
3781 class SeqOfType (SqType):
3782 def eth_type_default_table(self, ectx, tname):
3783 #print "eth_type_default_table(tname='%s')" % (tname)
3784 fname = ectx.eth_type[tname]['ref'][0]
3785 if self.val.IsNamed ():
3786 f = fname + '/' + self.val.name
3788 f = fname + '/' + '_item'
3791 table = "static const %(ER)s_sequence_t %(TABLE)s[1] = {\n"
3793 table = "static const %(ER)s_old_sequence_t %(TABLE)s[1] = {\n"
3795 table = "static const %(ER)s_sequence_t %(TABLE)s[1] = {\n"
3796 table += self.out_item(f, self.val, False, 'ASN1_NO_EXTENSIONS', ectx)
3800 #--- SequenceOfType -----------------------------------------------------------
3801 class SequenceOfType (SeqOfType):
3802 def to_python (self, ctx):
3803 # name, tag (None for no tag, EXPLICIT() for explicit), typ)
3804 # or '' + (1,) for optional
3806 if self.size_constr <> None:
3807 print "#Ignoring size constraint:", self.size_constr.subtype
3808 return "%sasn1.SEQUENCE_OF (%s%s)" % (ctx.spaces (),
3809 self.val.to_python (ctx),
3812 def eth_reg_sub(self, ident, ectx):
3814 if not self.val.IsNamed ():
3815 itmnm += '/' + '_item'
3816 self.val.eth_reg(itmnm, ectx, tstrip=1, idx='[##]', parent=ident)
3818 def eth_tname(self):
3819 if self.val.type != 'Type_Ref':
3820 return '#' + self.type + '_' + str(id(self))
3821 if not self.HasConstraint():
3822 return "SEQUENCE_OF_" + self.val.eth_tname()
3823 elif self.constr.IsSize():
3824 return 'SEQUENCE_' + self.constr.eth_constrname() + '_OF_' + self.val.eth_tname()
3826 return '#' + self.type + '_' + str(id(self))
3828 def eth_ftype(self, ectx):
3829 return ('FT_UINT32', 'BASE_DEC')
3831 def eth_need_tree(self):
3834 def GetTTag(self, ectx):
3835 return ('BER_CLASS_UNI', 'BER_UNI_TAG_SEQUENCE')
3837 def eth_type_default_pars(self, ectx, tname):
3838 pars = Type.eth_type_default_pars(self, ectx, tname)
3839 (pars['MIN_VAL'], pars['MAX_VAL'], pars['EXT']) = self.eth_get_size_constr(ectx)
3840 pars['TABLE'] = '%(PROTOP)s%(TNAME)s_sequence_of'
3843 def eth_type_default_body(self, ectx, tname):
3846 body = ectx.eth_fn_call('dissect_%(ER)s_sequence_of', ret='offset',
3847 par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'),
3848 ('%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s',),))
3850 body = ectx.eth_fn_call('dissect_%(ER)s_old_sequence_of', ret='offset',
3851 par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'),
3852 ('%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s',),))
3853 elif (ectx.Per() and not self.HasConstraint()):
3854 body = ectx.eth_fn_call('dissect_%(ER)s_sequence_of', ret='offset',
3855 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
3856 ('%(ETT_INDEX)s', '%(TABLE)s',),))
3857 elif (ectx.Per() and self.constr.type == 'Size'):
3858 body = ectx.eth_fn_call('dissect_%(ER)s_constrained_sequence_of', ret='offset',
3859 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
3860 ('%(ETT_INDEX)s', '%(TABLE)s',),
3861 ('%(MIN_VAL)s', '%(MAX_VAL)s',),))
3863 body = '#error Can not decode %s' % (tname)
3867 #--- SetOfType ----------------------------------------------------------------
3868 class SetOfType (SeqOfType):
3869 def eth_reg_sub(self, ident, ectx):
3871 if not self.val.IsNamed ():
3872 itmnm += '/' + '_item'
3873 self.val.eth_reg(itmnm, ectx, tstrip=1, idx='(##)', parent=ident)
3875 def eth_tname(self):
3876 if self.val.type != 'Type_Ref':
3877 return '#' + self.type + '_' + str(id(self))
3878 if not self.HasConstraint():
3879 return "SET_OF_" + self.val.eth_tname()
3880 elif self.constr.IsSize():
3881 return 'SET_' + self.constr.eth_constrname() + '_OF_' + self.val.eth_tname()
3883 return '#' + self.type + '_' + str(id(self))
3885 def eth_ftype(self, ectx):
3886 return ('FT_UINT32', 'BASE_DEC')
3888 def eth_need_tree(self):
3891 def GetTTag(self, ectx):
3892 return ('BER_CLASS_UNI', 'BER_UNI_TAG_SET')
3894 def eth_type_default_pars(self, ectx, tname):
3895 pars = Type.eth_type_default_pars(self, ectx, tname)
3896 (pars['MIN_VAL'], pars['MAX_VAL'], pars['EXT']) = self.eth_get_size_constr(ectx)
3897 pars['TABLE'] = '%(PROTOP)s%(TNAME)s_set_of'
3900 def eth_type_default_body(self, ectx, tname):
3903 body = ectx.eth_fn_call('dissect_%(ER)s_set_of', ret='offset',
3904 par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'),
3905 ('%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s',),))
3907 body = ectx.eth_fn_call('dissect_%(ER)s_old_set_of', ret='offset',
3908 par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'),
3909 ('%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s',),))
3910 elif (ectx.Per() and not self.HasConstraint()):
3911 body = ectx.eth_fn_call('dissect_%(ER)s_set_of', ret='offset',
3912 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
3913 ('%(ETT_INDEX)s', '%(TABLE)s',),))
3914 elif (ectx.Per() and self.constr.type == 'Size'):
3915 body = ectx.eth_fn_call('dissect_%(ER)s_constrained_set_of', ret='offset',
3916 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
3917 ('%(ETT_INDEX)s', '%(TABLE)s',),
3918 ('%(MIN_VAL)s', '%(MAX_VAL)s',),))
3920 body = '#error Can not decode %s' % (tname)
3923 def mk_tag_str (ctx, cls, typ, num):
3925 # XXX should do conversion to int earlier!
3928 if typ == 'DEFAULT':
3930 return 'asn1.%s(%d,cls=asn1.%s_FLAG)' % (typ, val, cls) # XXX still ned
3932 #--- SequenceType -------------------------------------------------------------
3933 class SequenceType (SeqType):
3934 def to_python (self, ctx):
3935 # name, tag (None for no tag, EXPLICIT() for explicit), typ)
3936 # or '' + (1,) for optional
3937 # XXX should also collect names for SEQUENCE inside SEQUENCE or
3938 # CHOICE or SEQUENCE_OF (where should the SEQUENCE_OF name come
3939 # from? for others, element or arm name would be fine)
3940 seq_name = getattr (self, 'sequence_name', None)
3941 if seq_name == None:
3944 seq_name = "'" + seq_name + "'"
3945 if self.__dict__.has_key('ext_list'):
3946 return "%sasn1.SEQUENCE ([%s], ext=[%s], seq_name = %s)" % (ctx.spaces (),
3947 self.elts_to_py (self.elt_list, ctx),
3948 self.elts_to_py (self.ext_list, ctx), seq_name)
3950 return "%sasn1.SEQUENCE ([%s]), seq_name = %s" % (ctx.spaces (),
3951 self.elts_to_py (self.elt_list, ctx), seq_name)
3952 def elts_to_py (self, list, ctx):
3953 # we have elt_type, val= named_type, maybe default=, optional=
3954 # named_type node: either ident = or typ =
3955 # need to dismember these in order to generate Python output syntax.
3958 assert (e.type == 'elt_type')
3960 optflag = e.optional
3961 #assert (not hasattr (e, 'default')) # XXX add support for DEFAULT!
3962 assert (nt.type == 'named_type')
3965 if hasattr (nt.typ, 'type') and nt.typ.type == 'tag': # ugh
3966 tagstr = mk_tag_str (ctx,nt.typ.tag.cls,
3967 nt.typ.tag.tag_typ,nt.typ.tag.num)
3971 return "('%s',%s,%s,%d)" % (identstr, tagstr,
3972 nt.typ.to_python (ctx), optflag)
3973 indentstr = ",\n" + ctx.spaces ()
3974 rv = indentstr.join ([elt_to_py (e) for e in list])
3978 def eth_reg_sub(self, ident, ectx, components_available=False):
3979 if self.need_components():
3980 if components_available:
3981 self.expand_components(ectx)
3983 ectx.eth_comp_req(ident)
3985 for e in (self.elt_list):
3986 e.val.eth_reg(ident, ectx, tstrip=1, parent=ident)
3987 if hasattr(self, 'ext_list'):
3988 for e in (self.ext_list):
3989 e.val.eth_reg(ident, ectx, tstrip=1, parent=ident)
3990 if hasattr(self, 'elt_list2'):
3991 for e in (self.elt_list2):
3992 e.val.eth_reg(ident, ectx, tstrip=1, parent=ident)
3994 def eth_need_tree(self):
3997 def GetTTag(self, ectx):
3998 return ('BER_CLASS_UNI', 'BER_UNI_TAG_SEQUENCE')
4000 def eth_type_default_pars(self, ectx, tname):
4001 pars = Type.eth_type_default_pars(self, ectx, tname)
4002 pars['TABLE'] = '%(PROTOP)s%(TNAME)s_sequence'
4005 def eth_type_default_body(self, ectx, tname):
4008 body = ectx.eth_fn_call('dissect_%(ER)s_sequence', ret='offset',
4009 par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'),
4010 ('%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s',),))
4012 body = ectx.eth_fn_call('dissect_%(ER)s_old_sequence', ret='offset',
4013 par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'),
4014 ('%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s',),))
4016 body = ectx.eth_fn_call('dissect_%(ER)s_sequence', ret='offset',
4017 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
4018 ('%(ETT_INDEX)s', '%(TABLE)s',),))
4020 body = '#error Can not decode %s' % (tname)
4023 #--- SetType ------------------------------------------------------------------
4024 class SetType(SeqType):
4026 def eth_reg_sub(self, ident, ectx, components_available=False):
4027 if self.need_components():
4028 if components_available:
4029 self.expand_components(ectx)
4031 ectx.eth_comp_req(ident)
4033 for e in (self.elt_list):
4034 e.val.eth_reg(ident, ectx, tstrip=1, parent=ident)
4035 if hasattr(self, 'ext_list'):
4036 for e in (self.ext_list):
4037 e.val.eth_reg(ident, ectx, tstrip=1, parent=ident)
4039 def eth_need_tree(self):
4042 def GetTTag(self, ectx):
4043 return ('BER_CLASS_UNI', 'BER_UNI_TAG_SET')
4045 def eth_type_default_pars(self, ectx, tname):
4046 pars = Type.eth_type_default_pars(self, ectx, tname)
4047 pars['TABLE'] = '%(PROTOP)s%(TNAME)s_set'
4050 def eth_type_default_body(self, ectx, tname):
4053 body = ectx.eth_fn_call('dissect_%(ER)s_set', ret='offset',
4054 par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'),
4055 ('%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s',),))
4057 body = ectx.eth_fn_call('dissect_%(ER)s_old_set', ret='offset',
4058 par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'),
4059 ('%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s',),))
4061 body = ectx.eth_fn_call('dissect_%(ER)s_set', ret='offset',
4062 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
4063 ('%(ETT_INDEX)s', '%(TABLE)s',),))
4065 body = '#error Can not decode %s' % (tname)
4068 #--- ChoiceType ---------------------------------------------------------------
4069 class ChoiceType (Type):
4070 def to_python (self, ctx):
4071 # name, tag (None for no tag, EXPLICIT() for explicit), typ)
4072 # or '' + (1,) for optional
4073 if self.__dict__.has_key('ext_list'):
4074 return "%sasn1.CHOICE ([%s], ext=[%s])" % (ctx.spaces (),
4075 self.elts_to_py (self.elt_list, ctx),
4076 self.elts_to_py (self.ext_list, ctx))
4078 return "%sasn1.CHOICE ([%s])" % (ctx.spaces (), self.elts_to_py (self.elt_list, ctx))
4079 def elts_to_py (self, list, ctx):
4082 assert (nt.type == 'named_type')
4084 if hasattr (nt, 'ident'):
4087 if hasattr (nt.typ, 'val'):
4088 identstr = nt.typ.val # XXX, making up name
4089 elif hasattr (nt.typ, 'name'):
4090 identstr = nt.typ.name
4092 identstr = ctx.make_new_name ()
4094 if hasattr (nt.typ, 'type') and nt.typ.type == 'tag': # ugh
4095 tagstr = mk_tag_str (ctx,nt.typ.tag.cls,
4096 nt.typ.tag.tag_typ,nt.typ.tag.num)
4100 return "('%s',%s,%s)" % (identstr, tagstr,
4101 nt.typ.to_python (ctx))
4102 indentstr = ",\n" + ctx.spaces ()
4103 rv = indentstr.join ([elt_to_py (e) for e in list])
4107 def eth_reg_sub(self, ident, ectx):
4108 #print "eth_reg_sub(ident='%s')" % (ident)
4109 for e in (self.elt_list):
4110 e.eth_reg(ident, ectx, tstrip=1, parent=ident)
4111 if ectx.conform.check_item('EXPORTS', ident + '.' + e.name):
4112 ectx.eth_sel_req(ident, e.name)
4113 if hasattr(self, 'ext_list'):
4114 for e in (self.ext_list):
4115 e.eth_reg(ident, ectx, tstrip=1, parent=ident)
4116 if ectx.conform.check_item('EXPORTS', ident + '.' + e.name):
4117 ectx.eth_sel_req(ident, e.name)
4119 def sel_item(self, ident, sel, ectx):
4120 lst = self.elt_list[:]
4121 if hasattr(self, 'ext_list'):
4122 lst.extend(self.ext_list)
4124 for e in (self.elt_list):
4125 if e.IsNamed() and (e.name == sel):
4129 print "#CHOICE %s does not contain item %s" % (ident, sel)
4132 def sel_req(self, ident, sel, ectx):
4133 #print "sel_req(ident='%s', sel=%s)\n%s" % (ident, sel, str(self))
4134 ee = self.sel_item(ident, sel, ectx)
4136 ee.eth_reg(ident, ectx, tstrip=0, selflag=True)
4138 def eth_ftype(self, ectx):
4139 return ('FT_UINT32', 'BASE_DEC')
4141 def eth_ftype_sel(self, sel, ectx):
4142 ee = self.sel_item('', sel, ectx)
4144 return ee.eth_ftype(ectx)
4146 return ('FT_NONE', 'BASE_NONE')
4148 def eth_strings(self):
4151 def eth_need_tree(self):
4154 def eth_has_vals(self):
4157 def GetTTag(self, ectx):
4159 cls = 'BER_CLASS_ANY/*choice*/'
4160 #if hasattr(self, 'ext_list'):
4161 # lst.extend(self.ext_list)
4163 # cls = lst[0].GetTag(ectx)[0]
4165 # if (e.GetTag(ectx)[0] != cls):
4166 # cls = '-1/*choice*/'
4167 return (cls, '-1/*choice*/')
4169 def GetTTagSel(self, sel, ectx):
4170 ee = self.sel_item('', sel, ectx)
4172 return ee.GetTag(ectx)
4174 return ('BER_CLASS_ANY/*unknown selection*/', '-1/*unknown selection*/')
4176 def IndetermTag(self, ectx):
4177 #print "Choice IndetermTag()=%s" % (str(not self.HasOwnTag()))
4178 return not self.HasOwnTag()
4180 def detect_tagval(self, ectx):
4182 lst = self.elt_list[:]
4183 if hasattr(self, 'ext_list'):
4184 lst.extend(self.ext_list)
4185 if (len(lst) > 0) and (not ectx.Per() or lst[0].HasOwnTag()):
4186 t = lst[0].GetTag(ectx)[0]
4191 if (t == 'BER_CLASS_UNI'):
4194 if not ectx.Per() or e.HasOwnTag():
4195 tt = e.GetTag(ectx)[0]
4203 def get_vals(self, ectx):
4204 tagval = self.detect_tagval(ectx)
4207 for e in (self.elt_list):
4208 if (tagval): val = e.GetTag(ectx)[1]
4209 else: val = str(cnt)
4210 vals.append((val, e.name))
4212 if hasattr(self, 'ext_list'):
4213 for e in (self.ext_list):
4214 if (tagval): val = e.GetTag(ectx)[1]
4215 else: val = str(cnt)
4216 vals.append((val, e.name))
4220 def eth_type_vals(self, tname, ectx):
4222 vals = self.get_vals(ectx)
4223 out += ectx.eth_vals(tname, vals)
4226 def eth_type_enum(self, tname, ectx):
4228 vals = self.get_vals(ectx)
4229 out += ectx.eth_enum(tname, vals)
4232 def eth_type_default_pars(self, ectx, tname):
4233 pars = Type.eth_type_default_pars(self, ectx, tname)
4234 pars['TABLE'] = '%(PROTOP)s%(TNAME)s_choice'
4237 def eth_type_default_table(self, ectx, tname):
4238 def out_item(val, e, ext, ectx):
4239 has_enum = ectx.eth_type[tname]['enum'] & EF_ENUM
4241 vval = ectx.eth_enum_item(tname, e.name)
4244 f = fname + '/' + e.name
4245 ef = ectx.field[f]['ethname']
4246 t = ectx.eth_hf[ef]['ethtype']
4248 if (ectx.field[f]['impl']):
4252 if (not e.HasOwnTag()):
4253 opt = 'BER_FLAGS_NOOWNTAG'
4254 elif (e.HasImplicitTag(ectx)):
4255 if (opt): opt += '|'
4256 opt += 'BER_FLAGS_IMPLTAG'
4257 if (not opt): opt = '0'
4259 (tc, tn) = e.GetTag(ectx)
4261 out = ' { %3s, %-24s, %-13s, %s, %s, dissect_%s_%s },\n' \
4262 % (vval, '&'+ectx.eth_hf[ef]['fullname'], tc, tn, opt, ectx.eth_type[t]['proto'], t)
4264 out = ' { %3s, %-13s, %s, %s, dissect_%s },\n' \
4265 % (vval, tc, tn, opt, efd)
4267 out = ' { %3s, %-24s, %-23s, dissect_%s_%s },\n' \
4268 % (vval, '&'+ectx.eth_hf[ef]['fullname'], ext, ectx.eth_type[t]['proto'], t)
4273 #print "eth_type_default_table(tname='%s')" % (tname)
4274 fname = ectx.eth_type[tname]['ref'][0]
4275 tagval = self.detect_tagval(ectx)
4278 table = "static const %(ER)s_choice_t %(TABLE)s[] = {\n"
4280 table = "static const %(ER)s_old_choice_t %(TABLE)s[] = {\n"
4282 table = "static const %(ER)s_choice_t %(TABLE)s[] = {\n"
4284 if hasattr(self, 'ext_list'):
4285 ext = 'ASN1_EXTENSION_ROOT'
4287 ext = 'ASN1_NO_EXTENSIONS'
4288 for e in (self.elt_list):
4289 if (tagval): val = e.GetTag(ectx)[1]
4290 else: val = str(cnt)
4291 table += out_item(val, e, ext, ectx)
4293 if hasattr(self, 'ext_list'):
4294 for e in (self.ext_list):
4295 if (tagval): val = e.GetTag(ectx)[1]
4296 else: val = str(cnt)
4297 table += out_item(val, e, 'ASN1_NOT_EXTENSION_ROOT', ectx)
4301 table += " { 0, NULL, 0, 0, 0, NULL }\n};\n"
4303 table += " { 0, 0, 0, 0, NULL }\n};\n"
4305 table += " { 0, NULL, 0, NULL }\n};\n"
4308 def eth_type_default_body(self, ectx, tname):
4311 body = ectx.eth_fn_call('dissect_%(ER)s_choice', ret='offset',
4312 par=(('%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'),
4313 ('%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s'),
4316 body = ectx.eth_fn_call('dissect_%(ER)s_old_choice', ret='offset',
4317 par=(('%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'),
4318 ('%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s'),
4321 body = ectx.eth_fn_call('dissect_%(ER)s_choice', ret='offset',
4322 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
4323 ('%(ETT_INDEX)s', '%(TABLE)s',),
4326 body = '#error Can not decode %s' % (tname)
4329 #--- ChoiceValue ----------------------------------------------------
4330 class ChoiceValue (Value):
4331 def to_str(self, ectx):
4332 return self.val.to_str(ectx)
4334 def fld_obj_eq(self, other):
4335 return isinstance(other, ChoiceValue) and (self.choice == other.choice) and (str(self.val.val) == str(other.val.val))
4337 #--- EnumeratedType -----------------------------------------------------------
4338 class EnumeratedType (Type):
4339 def to_python (self, ctx):
4340 def strify_one (named_num):
4341 return "%s=%s" % (named_num.ident, named_num.val)
4342 return "asn1.ENUM(%s)" % ",".join (map (strify_one, self.val))
4344 def eth_ftype(self, ectx):
4345 return ('FT_UINT32', 'BASE_DEC')
4347 def eth_strings(self):
4350 def eth_has_vals(self):
4353 def GetTTag(self, ectx):
4354 return ('BER_CLASS_UNI', 'BER_UNI_TAG_ENUMERATED')
4356 def get_vals_etc(self, ectx):
4364 for e in (self.val):
4365 if e.type == 'NamedNumber':
4366 used[int(e.val)] = True
4367 for e in (self.val):
4368 if e.type == 'NamedNumber':
4371 while used.has_key(lastv):
4375 vals.append((val, e.ident))
4376 map_table.append(val)
4380 if self.ext is not None:
4381 for e in (self.ext):
4382 if e.type == 'NamedNumber':
4383 used[int(e.val)] = True
4384 for e in (self.ext):
4385 if e.type == 'NamedNumber':
4388 while used.has_key(lastv):
4392 vals.append((val, e.ident))
4393 map_table.append(val)
4398 for i in range(len(map_table)):
4399 need_map = need_map or (map_table[i] != i)
4402 return (vals, root_num, ext_num, map_table)
4404 def eth_type_vals(self, tname, ectx):
4406 vals = self.get_vals_etc(ectx)[0]
4407 out += ectx.eth_vals(tname, vals)
4410 def reg_enum_vals(self, tname, ectx):
4411 vals = self.get_vals_etc(ectx)[0]
4412 for (val, id) in vals:
4413 ectx.eth_reg_value(id, self, val, ethname=ectx.eth_enum_item(tname, id))
4415 def eth_type_enum(self, tname, ectx):
4417 vals = self.get_vals_etc(ectx)[0]
4418 out += ectx.eth_enum(tname, vals)
4421 def eth_type_default_pars(self, ectx, tname):
4422 pars = Type.eth_type_default_pars(self, ectx, tname)
4423 (root_num, ext_num, map_table) = self.get_vals_etc(ectx)[1:]
4424 if (self.ext != None):
4428 pars['ROOT_NUM'] = str(root_num)
4430 pars['EXT_NUM'] = str(ext_num)
4432 pars['TABLE'] = '%(PROTOP)s%(TNAME)s_value_map'
4434 pars['TABLE'] = 'NULL'
4437 def eth_type_default_table(self, ectx, tname):
4438 if (not ectx.Per()): return ''
4439 map_table = self.get_vals_etc(ectx)[3]
4440 if (map_table == None): return ''
4441 table = "static guint32 %(TABLE)s[%(ROOT_NUM)s+%(EXT_NUM)s] = {"
4442 table += ", ".join([str(v) for v in map_table])
4446 def eth_type_default_body(self, ectx, tname):
4448 body = ectx.eth_fn_call('dissect_%(ER)s_integer', ret='offset',
4449 par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s'),
4452 body = ectx.eth_fn_call('dissect_%(ER)s_enumerated', ret='offset',
4453 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
4454 ('%(ROOT_NUM)s', '%(VAL_PTR)s', '%(EXT)s', '%(EXT_NUM)s', '%(TABLE)s',),))
4456 body = '#error Can not decode %s' % (tname)
4459 #--- EmbeddedPDVType -----------------------------------------------------------
4460 class EmbeddedPDVType (Type):
4461 def eth_tname(self):
4462 return 'EMBEDDED_PDV'
4464 def eth_ftype(self, ectx):
4465 return ('FT_NONE', 'BASE_NONE')
4467 def GetTTag(self, ectx):
4468 return ('BER_CLASS_UNI', 'BER_UNI_TAG_EMBEDDED_PDV')
4470 def eth_type_default_pars(self, ectx, tname):
4471 pars = Type.eth_type_default_pars(self, ectx, tname)
4472 if ectx.default_embedded_pdv_cb:
4473 pars['TYPE_REF_FN'] = ectx.default_embedded_pdv_cb
4475 pars['TYPE_REF_FN'] = 'NULL'
4478 def eth_type_default_body(self, ectx, tname):
4480 body = ectx.eth_fn_call('dissect_%(ER)s_EmbeddedPDV_Type', ret='offset',
4481 par=(('%(IMPLICIT_TAG)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(HF_INDEX)s', '%(TYPE_REF_FN)s',),))
4483 body = ectx.eth_fn_call('dissect_%(ER)s_embedded_pdv', ret='offset',
4484 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(TYPE_REF_FN)s',),))
4486 body = '#error Can not decode %s' % (tname)
4489 #--- ExternalType -----------------------------------------------------------
4490 class ExternalType (Type):
4491 def eth_tname(self):
4494 def eth_ftype(self, ectx):
4495 return ('FT_NONE', 'BASE_NONE')
4497 def GetTTag(self, ectx):
4498 return ('BER_CLASS_UNI', 'BER_UNI_TAG_EXTERNAL')
4500 def eth_type_default_pars(self, ectx, tname):
4501 pars = Type.eth_type_default_pars(self, ectx, tname)
4502 if ectx.default_external_type_cb:
4503 pars['TYPE_REF_FN'] = ectx.default_external_type_cb
4505 pars['TYPE_REF_FN'] = 'NULL'
4508 def eth_type_default_body(self, ectx, tname):
4510 body = ectx.eth_fn_call('dissect_%(ER)s_external_type', ret='offset',
4511 par=(('%(IMPLICIT_TAG)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(HF_INDEX)s', '%(TYPE_REF_FN)s',),))
4513 body = ectx.eth_fn_call('dissect_%(ER)s_external_type', ret='offset',
4514 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(TYPE_REF_FN)s',),))
4516 body = '#error Can not decode %s' % (tname)
4519 #--- OpenType -----------------------------------------------------------
4520 class OpenType (Type):
4521 def to_python (self, ctx):
4524 def single_type(self):
4525 if (self.HasConstraint() and
4526 self.constr.type == 'Type' and
4527 self.constr.subtype.type == 'Type_Ref'):
4528 return self.constr.subtype.val
4531 def eth_reg_sub(self, ident, ectx):
4532 t = self.single_type()
4534 ectx.eth_dep_add(ident, t)
4536 def eth_tname(self):
4537 t = self.single_type()
4539 return 'OpenType_' + t
4541 return Type.eth_tname(self)
4543 def eth_ftype(self, ectx):
4544 return ('FT_NONE', 'BASE_NONE')
4546 def GetTTag(self, ectx):
4547 return ('BER_CLASS_ANY', '0')
4549 def eth_type_default_pars(self, ectx, tname):
4550 pars = Type.eth_type_default_pars(self, ectx, tname)
4551 pars['FN_VARIANT'] = ectx.default_opentype_variant
4552 t = self.single_type()
4554 t = ectx.type[t]['ethname']
4555 pars['TYPE_REF_PROTO'] = ectx.eth_type[t]['proto']
4556 pars['TYPE_REF_TNAME'] = t
4557 pars['TYPE_REF_FN'] = 'dissect_%(TYPE_REF_PROTO)s_%(TYPE_REF_TNAME)s'
4559 pars['TYPE_REF_FN'] = 'NULL'
4562 def eth_type_default_body(self, ectx, tname):
4564 body = ectx.eth_fn_call('dissect_%(ER)s_open_type%(FN_VARIANT)s', ret='offset',
4565 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(TYPE_REF_FN)s',),))
4567 body = '#error Can not decode %s' % (tname)
4570 #--- InstanceOfType -----------------------------------------------------------
4571 class InstanceOfType (Type):
4572 def eth_tname(self):
4573 return 'INSTANCE_OF'
4575 def eth_ftype(self, ectx):
4576 return ('FT_NONE', 'BASE_NONE')
4578 def GetTTag(self, ectx):
4579 return ('BER_CLASS_UNI', 'BER_UNI_TAG_EXTERNAL')
4581 def eth_type_default_pars(self, ectx, tname):
4582 pars = Type.eth_type_default_pars(self, ectx, tname)
4583 if ectx.default_external_type_cb:
4584 pars['TYPE_REF_FN'] = ectx.default_external_type_cb
4586 pars['TYPE_REF_FN'] = 'NULL'
4589 def eth_type_default_body(self, ectx, tname):
4591 body = ectx.eth_fn_call('dissect_%(ER)s_external_type', ret='offset',
4592 par=(('%(IMPLICIT_TAG)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(HF_INDEX)s', '%(TYPE_REF_FN)s',),))
4594 body = '#error Can not decode %s' % (tname)
4596 body = '#error Can not decode %s' % (tname)
4599 #--- AnyType -----------------------------------------------------------
4600 class AnyType (Type):
4601 def to_python (self, ctx):
4604 def eth_ftype(self, ectx):
4605 return ('FT_NONE', 'BASE_NONE')
4607 def GetTTag(self, ectx):
4608 return ('BER_CLASS_ANY', '0')
4610 def eth_type_default_body(self, ectx, tname):
4611 body = '#error Can not decode %s' % (tname)
4614 class Literal (Node):
4615 def to_python (self, ctx):
4618 #--- NullType -----------------------------------------------------------------
4619 class NullType (Type):
4620 def to_python (self, ctx):
4623 def eth_tname(self):
4626 def GetTTag(self, ectx):
4627 return ('BER_CLASS_UNI', 'BER_UNI_TAG_NULL')
4629 def eth_type_default_body(self, ectx, tname):
4631 body = ectx.eth_fn_call('dissect_%(ER)s_null', ret='offset',
4632 par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s'),))
4634 body = ectx.eth_fn_call('dissect_%(ER)s_null', ret='offset',
4635 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),))
4637 body = '#error Can not decode %s' % (tname)
4640 #--- NullValue ----------------------------------------------------
4641 class NullValue (Value):
4642 def to_str(self, ectx):
4645 #--- RealType -----------------------------------------------------------------
4646 class RealType (Type):
4647 def to_python (self, ctx):
4650 def eth_tname(self):
4653 def GetTTag(self, ectx):
4654 return ('BER_CLASS_UNI', 'BER_UNI_TAG_REAL')
4656 def eth_ftype(self, ectx):
4657 return ('FT_DOUBLE', 'BASE_NONE')
4659 def eth_type_default_body(self, ectx, tname):
4661 body = ectx.eth_fn_call('dissect_%(ER)s_real', ret='offset',
4662 par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s'),
4665 body = ectx.eth_fn_call('dissect_%(ER)s_real', ret='offset',
4666 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),))
4668 body = '#error Can not decode %s' % (tname)
4671 #--- BooleanType --------------------------------------------------------------
4672 class BooleanType (Type):
4673 def to_python (self, ctx):
4674 return 'asn1.BOOLEAN'
4676 def eth_tname(self):
4679 def GetTTag(self, ectx):
4680 return ('BER_CLASS_UNI', 'BER_UNI_TAG_BOOLEAN')
4682 def eth_ftype(self, ectx):
4683 return ('FT_BOOLEAN', '8')
4685 def eth_type_default_body(self, ectx, tname):
4687 body = ectx.eth_fn_call('dissect_%(ER)s_boolean', ret='offset',
4688 par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s'),))
4690 body = ectx.eth_fn_call('dissect_%(ER)s_boolean', ret='offset',
4691 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),))
4693 body = '#error Can not decode %s' % (tname)
4696 #--- OctetStringType ----------------------------------------------------------
4697 class OctetStringType (Type):
4698 def to_python (self, ctx):
4699 return 'asn1.OCTSTRING'
4701 def eth_tname(self):
4702 if not self.HasConstraint():
4703 return 'OCTET_STRING'
4704 elif self.constr.type == 'Size':
4705 return 'OCTET_STRING' + '_' + self.constr.eth_constrname()
4707 return '#' + self.type + '_' + str(id(self))
4709 def eth_ftype(self, ectx):
4710 return ('FT_BYTES', 'BASE_HEX')
4712 def GetTTag(self, ectx):
4713 return ('BER_CLASS_UNI', 'BER_UNI_TAG_OCTETSTRING')
4715 def eth_need_pdu(self, ectx):
4717 if self.HasContentsConstraint():
4718 t = self.constr.GetContents(ectx)
4719 if t and (ectx.default_containing_variant in ('_pdu', '_pdu_new')):
4721 'new' : ectx.default_containing_variant == '_pdu_new' }
4724 def eth_type_default_pars(self, ectx, tname):
4725 pars = Type.eth_type_default_pars(self, ectx, tname)
4726 (pars['MIN_VAL'], pars['MAX_VAL'], pars['EXT']) = self.eth_get_size_constr(ectx)
4727 if self.HasContentsConstraint():
4728 pars['FN_VARIANT'] = ectx.default_containing_variant
4729 t = self.constr.GetContents(ectx)
4731 if pars['FN_VARIANT'] in ('_pdu', '_pdu_new'):
4732 t = ectx.field[t]['ethname']
4733 pars['TYPE_REF_PROTO'] = ''
4734 pars['TYPE_REF_TNAME'] = t
4735 pars['TYPE_REF_FN'] = 'dissect_%(TYPE_REF_TNAME)s'
4737 t = ectx.type[t]['ethname']
4738 pars['TYPE_REF_PROTO'] = ectx.eth_type[t]['proto']
4739 pars['TYPE_REF_TNAME'] = t
4740 pars['TYPE_REF_FN'] = 'dissect_%(TYPE_REF_PROTO)s_%(TYPE_REF_TNAME)s'
4742 pars['TYPE_REF_FN'] = 'NULL'
4745 def eth_type_default_body(self, ectx, tname):
4747 body = ectx.eth_fn_call('dissect_%(ER)s_octet_string', ret='offset',
4748 par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s'),
4751 if self.HasContentsConstraint():
4752 body = ectx.eth_fn_call('dissect_%(ER)s_octet_string_containing%(FN_VARIANT)s', ret='offset',
4753 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
4754 ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(TYPE_REF_FN)s',),))
4756 body = ectx.eth_fn_call('dissect_%(ER)s_octet_string', ret='offset',
4757 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
4758 ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(VAL_PTR)s',),))
4760 body = '#error Can not decode %s' % (tname)
4763 #--- CharacterStringType ------------------------------------------------------
4764 class CharacterStringType (Type):
4765 def eth_tname(self):
4766 if not self.HasConstraint():
4767 return self.eth_tsname()
4768 elif self.constr.type == 'Size':
4769 return self.eth_tsname() + '_' + self.constr.eth_constrname()
4771 return '#' + self.type + '_' + str(id(self))
4773 def eth_ftype(self, ectx):
4774 return ('FT_STRING', 'BASE_NONE')
4776 class RestrictedCharacterStringType (CharacterStringType):
4777 def to_python (self, ctx):
4778 return 'asn1.' + self.eth_tsname()
4780 def GetTTag(self, ectx):
4781 return ('BER_CLASS_UNI', 'BER_UNI_TAG_' + self.eth_tsname())
4783 def eth_type_default_pars(self, ectx, tname):
4784 pars = Type.eth_type_default_pars(self, ectx, tname)
4785 (pars['MIN_VAL'], pars['MAX_VAL'], pars['EXT']) = self.eth_get_size_constr(ectx)
4786 (pars['STRING_TYPE'], pars['STRING_TAG']) = (self.eth_tsname(), self.GetTTag(ectx)[1])
4787 (pars['ALPHABET'], pars['ALPHABET_LEN']) = self.eth_get_alphabet_constr(ectx)
4790 def eth_type_default_body(self, ectx, tname):
4792 body = ectx.eth_fn_call('dissect_%(ER)s_restricted_string', ret='offset',
4793 par=(('%(IMPLICIT_TAG)s', '%(STRING_TAG)s'),
4794 ('%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s'),
4796 elif (ectx.Per() and self.HasPermAlph()):
4797 body = ectx.eth_fn_call('dissect_%(ER)s_restricted_character_string', ret='offset',
4798 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
4799 ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(ALPHABET)s', '%(ALPHABET_LEN)s'),
4802 if (self.eth_tsname() == 'GeneralString'):
4803 body = ectx.eth_fn_call('dissect_%(ER)s_%(STRING_TYPE)s', ret='offset',
4804 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),))
4805 elif (self.eth_tsname() == 'GeneralizedTime'):
4806 body = ectx.eth_fn_call('dissect_%(ER)s_VisibleString', ret='offset',
4807 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
4808 ('%(MIN_VAL)s', '%(MAX_VAL)s',),))
4809 elif (self.eth_tsname() == 'UTCTime'):
4810 body = ectx.eth_fn_call('dissect_%(ER)s_VisibleString', ret='offset',
4811 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
4812 ('%(MIN_VAL)s', '%(MAX_VAL)s',),))
4814 body = ectx.eth_fn_call('dissect_%(ER)s_%(STRING_TYPE)s', ret='offset',
4815 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
4816 ('%(MIN_VAL)s', '%(MAX_VAL)s',),))
4818 body = '#error Can not decode %s' % (tname)
4821 class BMPStringType (RestrictedCharacterStringType):
4822 def eth_tsname(self):
4825 class GeneralStringType (RestrictedCharacterStringType):
4826 def eth_tsname(self):
4827 return 'GeneralString'
4829 class GraphicStringType (RestrictedCharacterStringType):
4830 def eth_tsname(self):
4831 return 'GraphicString'
4833 class IA5StringType (RestrictedCharacterStringType):
4834 def eth_tsname(self):
4837 class NumericStringType (RestrictedCharacterStringType):
4838 def eth_tsname(self):
4839 return 'NumericString'
4841 class PrintableStringType (RestrictedCharacterStringType):
4842 def eth_tsname(self):
4843 return 'PrintableString'
4845 class TeletexStringType (RestrictedCharacterStringType):
4846 def eth_tsname(self):
4847 return 'TeletexString'
4849 class T61StringType (RestrictedCharacterStringType):
4850 def eth_tsname(self):
4852 def GetTTag(self, ectx):
4853 return ('BER_CLASS_UNI', 'BER_UNI_TAG_TeletexString')
4855 class UniversalStringType (RestrictedCharacterStringType):
4856 def eth_tsname(self):
4857 return 'UniversalString'
4859 class UTF8StringType (RestrictedCharacterStringType):
4860 def eth_tsname(self):
4863 class VideotexStringType (RestrictedCharacterStringType):
4864 def eth_tsname(self):
4865 return 'VideotexString'
4867 class VisibleStringType (RestrictedCharacterStringType):
4868 def eth_tsname(self):
4869 return 'VisibleString'
4871 class ISO646StringType (RestrictedCharacterStringType):
4872 def eth_tsname(self):
4873 return 'ISO646String'
4874 def GetTTag(self, ectx):
4875 return ('BER_CLASS_UNI', 'BER_UNI_TAG_VisibleString')
4877 class UnrestrictedCharacterStringType (CharacterStringType):
4878 def to_python (self, ctx):
4879 return 'asn1.UnrestrictedCharacterString'
4880 def eth_tsname(self):
4881 return 'CHARACTER_STRING'
4883 #--- UsefulType ---------------------------------------------------------------
4884 class GeneralizedTime (RestrictedCharacterStringType):
4885 def eth_tsname(self):
4886 return 'GeneralizedTime'
4888 def eth_type_default_body(self, ectx, tname):
4890 body = ectx.eth_fn_call('dissect_%(ER)s_%(STRING_TYPE)s', ret='offset',
4891 par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s'),))
4894 return RestrictedCharacterStringType.eth_type_default_body(self, ectx, tname)
4896 class UTCTime (RestrictedCharacterStringType):
4897 def eth_tsname(self):
4900 class ObjectDescriptor (RestrictedCharacterStringType):
4901 def eth_tsname(self):
4902 return 'ObjectDescriptor'
4904 def eth_type_default_body(self, ectx, tname):
4906 body = RestrictedCharacterStringType.eth_type_default_body(self, ectx, tname)
4908 body = ectx.eth_fn_call('dissect_%(ER)s_object_descriptor', ret='offset',
4909 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),))
4911 body = '#error Can not decode %s' % (tname)
4914 #--- ObjectIdentifierType -----------------------------------------------------
4915 class ObjectIdentifierType (Type):
4916 def to_python (self, ctx):
4917 return 'asn1.OBJECT_IDENTIFIER'
4919 def eth_tname(self):
4920 return 'OBJECT_IDENTIFIER'
4922 def eth_ftype(self, ectx):
4923 return ('FT_OID', 'BASE_NONE')
4925 def GetTTag(self, ectx):
4926 return ('BER_CLASS_UNI', 'BER_UNI_TAG_OID')
4928 def eth_type_default_pars(self, ectx, tname):
4929 pars = Type.eth_type_default_pars(self, ectx, tname)
4930 pars['FN_VARIANT'] = ectx.default_oid_variant
4933 def eth_type_default_body(self, ectx, tname):
4935 body = ectx.eth_fn_call('dissect_%(ER)s_object_identifier%(FN_VARIANT)s', ret='offset',
4936 par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),))
4938 body = ectx.eth_fn_call('dissect_%(ER)s_object_identifier%(FN_VARIANT)s', ret='offset',
4939 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(VAL_PTR)s',),))
4941 body = '#error Can not decode %s' % (tname)
4944 #--- ObjectIdentifierValue ----------------------------------------------------
4945 class ObjectIdentifierValue (Value):
4946 def get_num(self, path, val):
4947 return str(oid_names.get(path + '/' + val, val))
4949 def to_str(self, ectx):
4954 for v in self.comp_list:
4955 if isinstance(v, Node) and (v.type == 'name_and_number'):
4960 vstr = self.get_num(path, v)
4961 if not first and not vstr.isdigit():
4962 vstr = ectx.value_get_val(vstr)
4967 out += ectx.value_get_eth(vstr) + '"'
4977 v = self.comp_list[0]
4978 if isinstance(v, Node) and (v.type == 'name_and_number'):
4983 vstr = self.get_num('', v)
4989 class NamedNumber(Node):
4990 def to_python (self, ctx):
4991 return "('%s',%s)" % (self.ident, self.val)
4993 class NamedNumListBase(Node):
4994 def to_python (self, ctx):
4995 return "asn1.%s_class ([%s])" % (self.asn1_typ,",".join (
4996 map (lambda x: x.to_python (ctx), self.named_list)))
4998 #--- IntegerType --------------------------------------------------------------
4999 class IntegerType (Type):
5000 def to_python (self, ctx):
5001 return "asn1.INTEGER_class ([%s])" % (",".join (
5002 map (lambda x: x.to_python (ctx), self.named_list)))
5004 def add_named_value(self, ident, val):
5005 e = NamedNumber(ident = ident, val = val)
5006 if not self.named_list:
5007 self.named_list = []
5008 self.named_list.append(e)
5010 def eth_tname(self):
5012 return Type.eth_tname(self)
5013 if not self.HasConstraint():
5015 elif self.constr.type == 'SingleValue' or self.constr.type == 'ValueRange':
5016 return 'INTEGER' + '_' + self.constr.eth_constrname()
5018 return 'INTEGER' + '_' + self.constr.eth_tname()
5020 def GetTTag(self, ectx):
5021 return ('BER_CLASS_UNI', 'BER_UNI_TAG_INTEGER')
5024 def eth_ftype(self, ectx):
5025 if self.HasConstraint():
5026 if not self.constr.IsNegativ():
5027 return ('FT_UINT32', 'BASE_DEC')
5028 return ('FT_INT32', 'BASE_DEC')
5030 def eth_strings(self):
5031 if (self.named_list):
5036 def eth_has_vals(self):
5037 if (self.named_list):
5042 def get_vals(self, ectx):
5044 for e in (self.named_list):
5045 vals.append((int(e.val), e.ident))
5048 def eth_type_vals(self, tname, ectx):
5049 if not self.eth_has_vals(): return ''
5051 vals = self.get_vals(ectx)
5052 out += ectx.eth_vals(tname, vals)
5055 def reg_enum_vals(self, tname, ectx):
5056 vals = self.get_vals(ectx)
5057 for (val, id) in vals:
5058 ectx.eth_reg_value(id, self, val, ethname=ectx.eth_enum_item(tname, id))
5060 def eth_type_enum(self, tname, ectx):
5061 if not self.eth_has_enum(tname, ectx): return ''
5063 vals = self.get_vals(ectx)
5064 out += ectx.eth_enum(tname, vals)
5067 def eth_type_default_pars(self, ectx, tname):
5068 pars = Type.eth_type_default_pars(self, ectx, tname)
5069 if self.HasValueConstraint():
5070 (pars['MIN_VAL'], pars['MAX_VAL'], pars['EXT']) = self.eth_get_value_constr(ectx)
5073 def eth_type_default_body(self, ectx, tname):
5075 body = ectx.eth_fn_call('dissect_%(ER)s_integer', ret='offset',
5076 par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s', '%(HF_INDEX)s'),
5078 elif (ectx.Per() and not self.HasValueConstraint()):
5079 body = ectx.eth_fn_call('dissect_%(ER)s_integer', ret='offset',
5080 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s', '%(VAL_PTR)s'),))
5081 elif (ectx.Per() and self.HasValueConstraint()):
5082 body = ectx.eth_fn_call('dissect_%(ER)s_constrained_integer', ret='offset',
5083 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
5084 ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(VAL_PTR)s', '%(EXT)s'),))
5086 body = '#error Can not decode %s' % (tname)
5089 #--- BitStringType ------------------------------------------------------------
5090 class BitStringType (Type):
5091 def to_python (self, ctx):
5092 return "asn1.BITSTRING_class ([%s])" % (",".join (
5093 map (lambda x: x.to_python (ctx), self.named_list)))
5095 def eth_tname(self):
5097 return Type.eth_tname(self)
5098 elif not self.HasConstraint():
5100 elif self.constr.IsSize():
5101 return 'BIT_STRING' + '_' + self.constr.eth_constrname()
5103 return '#' + self.type + '_' + str(id(self))
5105 def GetTTag(self, ectx):
5106 return ('BER_CLASS_UNI', 'BER_UNI_TAG_BITSTRING')
5108 def eth_ftype(self, ectx):
5109 return ('FT_BYTES', 'BASE_HEX')
5111 def eth_need_tree(self):
5112 return self.named_list
5114 def eth_need_pdu(self, ectx):
5116 if self.HasContentsConstraint():
5117 t = self.constr.GetContents(ectx)
5118 if t and (ectx.default_containing_variant in ('_pdu', '_pdu_new')):
5120 'new' : ectx.default_containing_variant == '_pdu_new' }
5123 def eth_named_bits(self):
5125 if (self.named_list):
5126 for e in (self.named_list):
5127 bits.append((int(e.val), e.ident))
5130 def eth_type_default_pars(self, ectx, tname):
5131 pars = Type.eth_type_default_pars(self, ectx, tname)
5132 (pars['MIN_VAL'], pars['MAX_VAL'], pars['EXT']) = self.eth_get_size_constr(ectx)
5133 if not pars.has_key('ETT_INDEX'):
5134 pars['ETT_INDEX'] = '-1'
5135 pars['TABLE'] = 'NULL'
5136 if self.eth_named_bits():
5137 pars['TABLE'] = '%(PROTOP)s%(TNAME)s_bits'
5138 if self.HasContentsConstraint():
5139 pars['FN_VARIANT'] = ectx.default_containing_variant
5140 t = self.constr.GetContents(ectx)
5142 if pars['FN_VARIANT'] in ('_pdu', '_pdu_new'):
5143 t = ectx.field[t]['ethname']
5144 pars['TYPE_REF_PROTO'] = ''
5145 pars['TYPE_REF_TNAME'] = t
5146 pars['TYPE_REF_FN'] = 'dissect_%(TYPE_REF_TNAME)s'
5148 t = ectx.type[t]['ethname']
5149 pars['TYPE_REF_PROTO'] = ectx.eth_type[t]['proto']
5150 pars['TYPE_REF_TNAME'] = t
5151 pars['TYPE_REF_FN'] = 'dissect_%(TYPE_REF_PROTO)s_%(TYPE_REF_TNAME)s'
5153 pars['TYPE_REF_FN'] = 'NULL'
5156 def eth_type_default_table(self, ectx, tname):
5157 #print "eth_type_default_table(tname='%s')" % (tname)
5159 bits = self.eth_named_bits()
5160 if (bits and ectx.Ber()):
5161 table = ectx.eth_bits(tname, bits)
5164 def eth_type_default_body(self, ectx, tname):
5166 body = ectx.eth_fn_call('dissect_%(ER)s_bitstring', ret='offset',
5167 par=(('%(IMPLICIT_TAG)s', '%(ACTX)s', '%(TREE)s', '%(TVB)s', '%(OFFSET)s'),
5168 ('%(TABLE)s', '%(HF_INDEX)s', '%(ETT_INDEX)s',),
5171 if self.HasContentsConstraint():
5172 body = ectx.eth_fn_call('dissect_%(ER)s_bit_string_containing%(FN_VARIANT)s', ret='offset',
5173 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
5174 ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(EXT)s', '%(TYPE_REF_FN)s'),))
5176 body = ectx.eth_fn_call('dissect_%(ER)s_bit_string', ret='offset',
5177 par=(('%(TVB)s', '%(OFFSET)s', '%(ACTX)s', '%(TREE)s', '%(HF_INDEX)s'),
5178 ('%(MIN_VAL)s', '%(MAX_VAL)s', '%(EXT)s', '%(VAL_PTR)s'),))
5180 body = '#error Can not decode %s' % (tname)
5183 #--- BStringValue ------------------------------------------------------------
5202 class BStringValue (Value):
5203 def to_str(self, ectx):
5206 v += '0' * (8 - len(v) % 8)
5208 for i in (range(0, len(v), 4)):
5209 vv += bstring_tab[v[i:i+4]]
5212 #--- HStringValue ------------------------------------------------------------
5213 class HStringValue (Value):
5214 def to_str(self, ectx):
5216 vv += self.val[1:-2]
5219 #--- FieldSpec ----------------------------------------------------------------
5220 class FieldSpec (Node):
5221 def __init__(self,*args, **kw) :
5223 Node.__init__ (self,*args, **kw)
5225 def SetName(self, name):
5229 return ['#UNSUPPORTED_' + self.type]
5233 repr.extend(self.get_repr())
5236 class TypeFieldSpec (FieldSpec):
5240 class FixedTypeValueFieldSpec (FieldSpec):
5242 if isinstance(self.typ, Type_Ref):
5243 repr = ['TypeReference', self.typ.val]
5245 repr = [self.typ.type]
5248 class FixedTypeValueSetFieldSpec (FieldSpec):
5251 class ObjectFieldSpec (FieldSpec):
5253 return ['ClassReference', self.cls]
5255 class ObjectSetFieldSpec (FieldSpec):
5257 return ['ClassReference', self.cls]
5259 #==============================================================================
5261 def p_module_list_1 (t):
5262 'module_list : module_list ModuleDefinition'
5263 t[0] = t[1] + [t[2]]
5265 def p_module_list_2 (t):
5266 'module_list : ModuleDefinition'
5270 #--- ITU-T Recommendation X.680 -----------------------------------------------
5273 # 11 ASN.1 lexical items --------------------------------------------------------
5275 # 11.2 Type references
5277 'type_ref : UCASE_IDENT'
5278 t[0] = Type_Ref(val=t[1])
5281 def p_identifier (t):
5282 'identifier : LCASE_IDENT'
5285 # 11.4 Value references
5286 def p_valuereference (t):
5287 'valuereference : LCASE_IDENT'
5288 t[0] = Value_Ref(val=t[1])
5290 # 11.5 Module references
5291 def p_modulereference (t):
5292 'modulereference : UCASE_IDENT'
5296 # 12 Module definition --------------------------------------------------------
5299 def p_ModuleDefinition (t):
5300 'ModuleDefinition : ModuleIdentifier DEFINITIONS TagDefault ASSIGNMENT BEGIN ModuleBody END'
5301 t[0] = Module (ident = t[1], tag_def = t[3], body = t[6])
5303 def p_TagDefault_1 (t):
5304 '''TagDefault : EXPLICIT TAGS
5307 t[0] = Default_Tags (dfl_tag = t[1])
5309 def p_TagDefault_2 (t):
5311 # 12.2 The "TagDefault" is taken as EXPLICIT TAGS if it is "empty".
5312 t[0] = Default_Tags (dfl_tag = 'EXPLICIT')
5314 def p_ModuleIdentifier_1 (t):
5315 'ModuleIdentifier : modulereference DefinitiveIdentifier' # name, oid
5316 t [0] = Node('module_ident', val = t[1], ident = t[2])
5318 def p_ModuleIdentifier_2 (t):
5319 'ModuleIdentifier : modulereference' # name, oid
5320 t [0] = Node('module_ident', val = t[1], ident = None)
5322 def p_DefinitiveIdentifier (t):
5323 'DefinitiveIdentifier : ObjectIdentifierValue'
5326 #def p_module_ref (t):
5327 # 'module_ref : UCASE_IDENT'
5330 def p_ModuleBody_1 (t):
5331 'ModuleBody : Exports Imports AssignmentList'
5332 t[0] = Module_Body (exports = t[1], imports = t[2], assign_list = t[3])
5334 def p_ModuleBody_2 (t):
5336 t[0] = Node ('module_body', exports = [], imports = [], assign_list = [])
5338 def p_Exports_1 (t):
5339 'Exports : EXPORTS syms_exported SEMICOLON'
5342 def p_Exports_2 (t):
5343 'Exports : EXPORTS ALL SEMICOLON'
5346 def p_Exports_3 (t):
5350 def p_syms_exported_1 (t):
5351 'syms_exported : exp_sym_list'
5354 def p_syms_exported_2 (t):
5358 def p_exp_sym_list_1 (t):
5359 'exp_sym_list : Symbol'
5362 def p_exp_sym_list_2 (t):
5363 'exp_sym_list : exp_sym_list COMMA Symbol'
5364 t[0] = t[1] + [t[3]]
5367 def p_Imports_1 (t):
5368 'Imports : importsbegin IMPORTS SymbolsImported SEMICOLON'
5370 global lcase_ident_assigned
5371 lcase_ident_assigned = {}
5373 def p_importsbegin (t):
5375 global lcase_ident_assigned
5377 lcase_ident_assigned = {}
5378 lcase_ident_assigned.update(g_conform.use_item('ASSIGNED_ID', 'OBJECT_IDENTIFIER'))
5380 def p_Imports_2 (t):
5384 def p_SymbolsImported_1(t):
5385 'SymbolsImported : '
5388 def p_SymbolsImported_2 (t):
5389 'SymbolsImported : SymbolsFromModuleList'
5392 def p_SymbolsFromModuleList_1 (t):
5393 'SymbolsFromModuleList : SymbolsFromModuleList SymbolsFromModule'
5394 t[0] = t[1] + [t[2]]
5396 def p_SymbolsFromModuleList_2 (t):
5397 'SymbolsFromModuleList : SymbolsFromModule'
5400 def p_SymbolsFromModule (t):
5401 'SymbolsFromModule : SymbolList FROM GlobalModuleReference'
5402 t[0] = Node ('SymbolList', symbol_list = t[1], module = t[3])
5403 for s in (t[0].symbol_list):
5404 if (isinstance(s, Value_Ref)): lcase_ident_assigned[s.val] = t[3]
5405 if t[0].module.val == 'Remote-Operations-Information-Objects':
5406 for i in range(len(t[0].symbol_list)):
5407 s = t[0].symbol_list[i]
5408 if isinstance(s, Type_Ref) or isinstance(s, Class_Ref):
5410 if isinstance(s, Type_Ref) and is_class_ident(s.val):
5411 t[0].symbol_list[i] = Class_Ref (val = s.val)
5413 def p_GlobalModuleReference (t):
5414 'GlobalModuleReference : modulereference AssignedIdentifier'
5415 t [0] = Node('module_ident', val = t[1], ident = t[2])
5417 def p_AssignedIdentifier_1 (t):
5418 'AssignedIdentifier : ObjectIdentifierValue'
5421 def p_AssignedIdentifier_2 (t):
5422 'AssignedIdentifier : LCASE_IDENT_ASSIGNED'
5425 def p_AssignedIdentifier_3 (t):
5426 'AssignedIdentifier : '
5429 def p_SymbolList_1 (t):
5430 'SymbolList : Symbol'
5433 def p_SymbolList_2 (t):
5434 'SymbolList : SymbolList COMMA Symbol'
5435 t[0] = t[1] + [t[3]]
5438 '''Symbol : Reference
5439 | ParameterizedReference'''
5442 def p_Reference_1 (t):
5443 '''Reference : type_ref
5445 | objectclassreference '''
5448 def p_Reference_2 (t):
5449 '''Reference : LCASE_IDENT_ASSIGNED'''
5450 t[0] = Value_Ref (val=t[1])
5452 def p_AssignmentList_1 (t):
5453 'AssignmentList : AssignmentList Assignment'
5454 t[0] = t[1] + [t[2]]
5456 def p_AssignmentList_2 (t):
5457 'AssignmentList : Assignment SEMICOLON'
5460 def p_AssignmentList_3 (t):
5461 'AssignmentList : Assignment'
5464 def p_Assignment (t):
5465 '''Assignment : TypeAssignment
5467 | ValueSetTypeAssignment
5468 | ObjectClassAssignment
5470 | ObjectSetAssignment
5471 | ParameterizedAssignment
5476 # 13 Referencing type and value definitions -----------------------------------
5479 def p_DefinedType (t):
5480 '''DefinedType : ExternalTypeReference
5482 | ParameterizedType'''
5485 def p_DefinedValue(t):
5486 '''DefinedValue : ExternalValueReference
5491 def p_ExternalTypeReference (t):
5492 'ExternalTypeReference : modulereference DOT type_ref'
5493 t[0] = Node ('ExternalTypeReference', module = t[1], typ = t[3])
5495 def p_ExternalValueReference (t):
5496 'ExternalValueReference : modulereference DOT identifier'
5497 t[0] = Node ('ExternalValueReference', module = t[1], ident = t[3])
5500 # 15 Assigning types and values -----------------------------------------------
5503 def p_TypeAssignment (t):
5504 'TypeAssignment : UCASE_IDENT ASSIGNMENT Type'
5509 def p_ValueAssignment (t):
5510 'ValueAssignment : LCASE_IDENT ValueType ASSIGNMENT Value'
5511 t[0] = ValueAssignment(ident = t[1], typ = t[2], val = t[4])
5513 # only "simple" types are supported to simplify grammer
5514 def p_ValueType (t):
5515 '''ValueType : type_ref
5518 | ObjectIdentifierType
5525 def p_ValueSetTypeAssignment (t):
5526 'ValueSetTypeAssignment : UCASE_IDENT ValueType ASSIGNMENT ValueSet'
5527 t[0] = Node('ValueSetTypeAssignment', name=t[1], typ=t[2], val=t[4])
5531 'ValueSet : lbraceignore rbraceignore'
5535 # 16 Definition of types and values -------------------------------------------
5539 '''Type : BuiltinType
5541 | ConstrainedType'''
5545 def p_BuiltinType (t):
5546 '''BuiltinType : AnyType
5549 | CharacterStringType
5557 | ObjectClassFieldType
5558 | ObjectIdentifierType
5569 def p_ReferencedType (t):
5570 '''ReferencedType : DefinedType
5576 def p_NamedType (t):
5577 'NamedType : identifier Type'
5583 '''Value : BuiltinValue
5585 | ObjectClassFieldValue'''
5589 def p_BuiltinValue (t):
5590 '''BuiltinValue : BooleanValue
5593 | ObjectIdentifierValue
5598 | char_string''' # XXX we don't support {data} here
5602 def p_ReferencedValue (t):
5603 '''ReferencedValue : DefinedValue
5604 | ValueFromObject'''
5608 #def p_NamedValue (t):
5609 # 'NamedValue : identifier Value'
5610 # t[0] = Node ('NamedValue', ident = t[1], value = t[2])
5613 # 17 Notation for the boolean type --------------------------------------------
5616 def p_BooleanType (t):
5617 'BooleanType : BOOLEAN'
5618 t[0] = BooleanType ()
5621 def p_BooleanValue (t):
5622 '''BooleanValue : TRUE
5627 # 18 Notation for the integer type --------------------------------------------
5630 def p_IntegerType_1 (t):
5631 'IntegerType : INTEGER'
5632 t[0] = IntegerType (named_list = None)
5634 def p_IntegerType_2 (t):
5635 'IntegerType : INTEGER LBRACE NamedNumberList RBRACE'
5636 t[0] = IntegerType(named_list = t[3])
5638 def p_NamedNumberList_1 (t):
5639 'NamedNumberList : NamedNumber'
5642 def p_NamedNumberList_2 (t):
5643 'NamedNumberList : NamedNumberList COMMA NamedNumber'
5644 t[0] = t[1] + [t[3]]
5646 def p_NamedNumber (t):
5647 '''NamedNumber : identifier LPAREN SignedNumber RPAREN
5648 | identifier LPAREN DefinedValue RPAREN'''
5649 t[0] = NamedNumber(ident = t[1], val = t[3])
5651 def p_SignedNumber_1 (t):
5652 'SignedNumber : NUMBER'
5655 def p_SignedNumber_2 (t):
5656 'SignedNumber : MINUS NUMBER'
5660 def p_IntegerValue (t):
5661 'IntegerValue : SignedNumber'
5664 # 19 Notation for the enumerated type -----------------------------------------
5667 def p_EnumeratedType (t):
5668 'EnumeratedType : ENUMERATED LBRACE Enumerations RBRACE'
5669 t[0] = EnumeratedType (val = t[3]['val'], ext = t[3]['ext'])
5671 def p_Enumerations_1 (t):
5672 'Enumerations : Enumeration'
5673 t[0] = { 'val' : t[1], 'ext' : None }
5675 def p_Enumerations_2 (t):
5676 'Enumerations : Enumeration COMMA ELLIPSIS ExceptionSpec'
5677 t[0] = { 'val' : t[1], 'ext' : [] }
5679 def p_Enumerations_3 (t):
5680 'Enumerations : Enumeration COMMA ELLIPSIS ExceptionSpec COMMA Enumeration'
5681 t[0] = { 'val' : t[1], 'ext' : t[6] }
5683 def p_Enumeration_1 (t):
5684 'Enumeration : EnumerationItem'
5687 def p_Enumeration_2 (t):
5688 'Enumeration : Enumeration COMMA EnumerationItem'
5689 t[0] = t[1] + [t[3]]
5691 def p_EnumerationItem (t):
5692 '''EnumerationItem : Identifier
5696 def p_Identifier (t):
5697 'Identifier : identifier'
5698 t[0] = Node ('Identifier', ident = t[1])
5701 # 20 Notation for the real type -----------------------------------------------
5709 def p_RealValue (t):
5710 '''RealValue : REAL_NUMBER
5711 | SpecialRealValue'''
5714 def p_SpecialRealValue (t):
5715 '''SpecialRealValue : PLUS_INFINITY
5720 # 21 Notation for the bitstring type ------------------------------------------
5723 def p_BitStringType_1 (t):
5724 'BitStringType : BIT STRING'
5725 t[0] = BitStringType (named_list = None)
5727 def p_BitStringType_2 (t):
5728 'BitStringType : BIT STRING LBRACE NamedBitList RBRACE'
5729 t[0] = BitStringType (named_list = t[4])
5731 def p_NamedBitList_1 (t):
5732 'NamedBitList : NamedBit'
5735 def p_NamedBitList_2 (t):
5736 'NamedBitList : NamedBitList COMMA NamedBit'
5737 t[0] = t[1] + [t[3]]
5740 '''NamedBit : identifier LPAREN NUMBER RPAREN
5741 | identifier LPAREN DefinedValue RPAREN'''
5742 t[0] = NamedNumber (ident = t[1], val = t[3])
5745 # 22 Notation for the octetstring type ----------------------------------------
5748 def p_OctetStringType (t):
5749 'OctetStringType : OCTET STRING'
5750 t[0] = OctetStringType ()
5753 # 23 Notation for the null type -----------------------------------------------
5761 def p_NullValue (t):
5766 # 24 Notation for sequence types ----------------------------------------------
5769 def p_SequenceType_1 (t):
5770 'SequenceType : SEQUENCE LBRACE RBRACE'
5771 t[0] = SequenceType (elt_list = [])
5773 def p_SequenceType_2 (t):
5774 'SequenceType : SEQUENCE LBRACE ComponentTypeLists RBRACE'
5775 t[0] = SequenceType (elt_list = t[3]['elt_list'])
5776 if t[3].has_key('ext_list'):
5777 t[0].ext_list = t[3]['ext_list']
5778 if t[3].has_key('elt_list2'):
5779 t[0].ext_list = t[3]['elt_list2']
5781 def p_ExtensionAndException_1 (t):
5782 'ExtensionAndException : ELLIPSIS'
5785 def p_OptionalExtensionMarker_1 (t):
5786 'OptionalExtensionMarker : COMMA ELLIPSIS'
5789 def p_OptionalExtensionMarker_2 (t):
5790 'OptionalExtensionMarker : '
5793 def p_ComponentTypeLists_1 (t):
5794 'ComponentTypeLists : ComponentTypeList'
5795 t[0] = {'elt_list' : t[1]}
5797 def p_ComponentTypeLists_2 (t):
5798 'ComponentTypeLists : ComponentTypeList COMMA ExtensionAndException OptionalExtensionMarker'
5799 t[0] = {'elt_list' : t[1], 'ext_list' : []}
5801 def p_ComponentTypeLists_3 (t):
5802 'ComponentTypeLists : ComponentTypeList COMMA ExtensionAndException ExtensionAdditionList OptionalExtensionMarker'
5803 t[0] = {'elt_list' : t[1], 'ext_list' : t[4]}
5805 def p_ComponentTypeLists_4 (t):
5806 'ComponentTypeLists : ComponentTypeList COMMA ExtensionAndException ExtensionEndMarker COMMA ComponentTypeList'
5807 t[0] = {'elt_list' : t[1], 'ext_list' : [], 'elt_list2' : t[6]}
5809 def p_ComponentTypeLists_5 (t):
5810 'ComponentTypeLists : ComponentTypeList COMMA ExtensionAndException ExtensionAdditionList ExtensionEndMarker COMMA ComponentTypeList'
5811 t[0] = {'elt_list' : t[1], 'ext_list' : t[4], 'elt_list2' : t[7]}
5813 def p_ComponentTypeLists_6 (t):
5814 'ComponentTypeLists : ExtensionAndException OptionalExtensionMarker'
5815 t[0] = {'elt_list' : [], 'ext_list' : []}
5817 def p_ComponentTypeLists_7 (t):
5818 'ComponentTypeLists : ExtensionAndException ExtensionAdditionList OptionalExtensionMarker'
5819 t[0] = {'elt_list' : [], 'ext_list' : t[2]}
5821 #def p_RootComponentTypeList (t):
5822 # 'RootComponentTypeList : ComponentTypeList'
5825 def p_ExtensionEndMarker (t):
5826 'ExtensionEndMarker : COMMA ELLIPSIS'
5829 #def p_extension_additions_1 (t):
5830 # 'extension_additions : extension_addition_list'
5833 #def p_extension_additions_2 (t):
5834 # 'extension_additions : '
5837 def p_ExtensionAdditionList_1 (t):
5838 'ExtensionAdditionList : COMMA extension_addition'
5841 def p_ExtensionAdditionList_2 (t):
5842 'ExtensionAdditionList : ExtensionAdditionList COMMA extension_addition'
5843 t[0] = t[1] + [t[3]]
5845 def p_extension_addition_1 (t):
5846 'extension_addition : ComponentType'
5849 def p_ComponentTypeList_1 (t):
5850 'ComponentTypeList : ComponentType'
5853 def p_ComponentTypeList_2 (t):
5854 'ComponentTypeList : ComponentTypeList COMMA ComponentType'
5855 t[0] = t[1] + [t[3]]
5857 def p_ComponentType_1 (t):
5858 'ComponentType : NamedType'
5859 t[0] = Node ('elt_type', val = t[1], optional = 0)
5861 def p_ComponentType_2 (t):
5862 'ComponentType : NamedType OPTIONAL'
5863 t[0] = Node ('elt_type', val = t[1], optional = 1)
5865 def p_ComponentType_3 (t):
5866 'ComponentType : NamedType DEFAULT DefaultValue'
5867 t[0] = Node ('elt_type', val = t[1], optional = 1, default = t[3])
5869 def p_ComponentType_4 (t):
5870 'ComponentType : COMPONENTS OF Type'
5871 t[0] = Node ('components_of', typ = t[3])
5873 def p_DefaultValue_1 (t):
5874 '''DefaultValue : ReferencedValue
5882 | ObjectClassFieldValue'''
5885 def p_DefaultValue_2 (t):
5886 'DefaultValue : lbraceignore rbraceignore'
5890 def p_SequenceValue_1 (t):
5891 'SequenceValue : LBRACE RBRACE'
5895 #def p_SequenceValue_2 (t):
5896 # 'SequenceValue : LBRACE ComponentValueList RBRACE'
5899 #def p_ComponentValueList_1 (t):
5900 # 'ComponentValueList : NamedValue'
5903 #def p_ComponentValueList_2 (t):
5904 # 'ComponentValueList : ComponentValueList COMMA NamedValue'
5905 # t[0] = t[1] + [t[3]]
5908 # 25 Notation for sequence-of types -------------------------------------------
5911 def p_SequenceOfType (t):
5912 '''SequenceOfType : SEQUENCE OF Type
5913 | SEQUENCE OF NamedType'''
5914 t[0] = SequenceOfType (val = t[3], size_constr = None)
5917 # 26 Notation for set types ---------------------------------------------------
5920 def p_SetType_1 (t):
5921 'SetType : SET LBRACE RBRACE'
5922 t[0] = SetType (elt_list = [])
5924 def p_SetType_2 (t):
5925 'SetType : SET LBRACE ComponentTypeLists RBRACE'
5926 if t[3].has_key('ext_list'):
5927 t[0] = SetType (elt_list = t[3]['elt_list'], ext_list = t[3]['ext_list'])
5929 t[0] = SetType (elt_list = t[3]['elt_list'])
5932 # 27 Notation for set-of types ------------------------------------------------
5935 def p_SetOfType (t):
5936 '''SetOfType : SET OF Type
5937 | SET OF NamedType'''
5938 t[0] = SetOfType (val = t[3])
5940 # 28 Notation for choice types ------------------------------------------------
5943 def p_ChoiceType (t):
5944 'ChoiceType : CHOICE LBRACE alternative_type_lists RBRACE'
5945 if t[3].has_key('ext_list'):
5946 t[0] = ChoiceType (elt_list = t[3]['elt_list'], ext_list = t[3]['ext_list'])
5948 t[0] = ChoiceType (elt_list = t[3]['elt_list'])
5950 def p_alternative_type_lists_1 (t):
5951 'alternative_type_lists : alternative_type_list'
5952 t[0] = {'elt_list' : t[1]}
5954 def p_alternative_type_lists_2 (t):
5955 '''alternative_type_lists : alternative_type_list COMMA ExtensionAndException extension_addition_alternatives OptionalExtensionMarker'''
5956 t[0] = {'elt_list' : t[1], 'ext_list' : t[4]}
5958 def p_extension_addition_alternatives_1 (t):
5959 'extension_addition_alternatives : extension_addition_alternatives_list'
5962 def p_extension_addition_alternatives_2 (t):
5963 'extension_addition_alternatives : '
5966 def p_extension_addition_alternatives_list_1 (t):
5967 'extension_addition_alternatives_list : COMMA extension_addition_alternative'
5970 def p_extension_addition_alternatives_list_2 (t):
5971 'extension_addition_alternatives_list : extension_addition_alternatives_list COMMA extension_addition_alternative'
5972 t[0] = t[1] + [t[3]]
5974 def p_extension_addition_alternative_1 (t):
5975 'extension_addition_alternative : NamedType'
5978 def p_alternative_type_list_1 (t):
5979 'alternative_type_list : NamedType'
5982 def p_alternative_type_list_2 (t):
5983 'alternative_type_list : alternative_type_list COMMA NamedType'
5984 t[0] = t[1] + [t[3]]
5987 def p_ChoiceValue_1 (t):
5988 '''ChoiceValue : identifier COLON Value
5989 | identifier COLON NullValue '''
5991 if not isinstance(val, Value):
5992 val = Value(val=val)
5993 t[0] = ChoiceValue (choice = t[1], val = val)
5995 # 29 Notation for selection types
5998 def p_SelectionType (t): #
5999 'SelectionType : identifier LT Type'
6000 t[0] = SelectionType (typ = t[3], sel = t[1])
6002 # 30 Notation for tagged types ------------------------------------------------
6005 def p_TaggedType_1 (t):
6006 'TaggedType : Tag Type'
6007 t[1].mode = 'default'
6011 def p_TaggedType_2 (t):
6012 '''TaggedType : Tag IMPLICIT Type
6013 | Tag EXPLICIT Type'''
6019 'Tag : LBRACK Class ClassNumber RBRACK'
6020 t[0] = Tag(cls = t[2], num = t[3])
6022 def p_ClassNumber_1 (t):
6023 'ClassNumber : number'
6026 def p_ClassNumber_2 (t):
6027 'ClassNumber : DefinedValue'
6031 '''Class : UNIVERSAL
6046 # 31 Notation for the object identifier type ----------------------------------
6049 def p_ObjectIdentifierType (t):
6050 'ObjectIdentifierType : OBJECT IDENTIFIER'
6051 t[0] = ObjectIdentifierType()
6054 def p_ObjectIdentifierValue (t):
6055 'ObjectIdentifierValue : LBRACE oid_comp_list RBRACE'
6056 t[0] = ObjectIdentifierValue (comp_list=t[2])
6058 def p_oid_comp_list_1 (t):
6059 'oid_comp_list : oid_comp_list ObjIdComponents'
6060 t[0] = t[1] + [t[2]]
6062 def p_oid_comp_list_2 (t):
6063 'oid_comp_list : ObjIdComponents'
6066 def p_ObjIdComponents (t):
6067 '''ObjIdComponents : NameForm
6069 | NameAndNumberForm'''
6073 '''NameForm : LCASE_IDENT
6074 | LCASE_IDENT_ASSIGNED'''
6077 def p_NumberForm (t):
6078 '''NumberForm : NUMBER'''
6082 def p_NameAndNumberForm (t):
6083 '''NameAndNumberForm : LCASE_IDENT_ASSIGNED LPAREN NumberForm RPAREN
6084 | LCASE_IDENT LPAREN NumberForm RPAREN'''
6085 t[0] = Node('name_and_number', ident = t[1], number = t[3])
6087 # 33 Notation for the embedded-pdv type -------------------------------------------
6089 def p_EmbeddedPDVType (t):
6090 'EmbeddedPDVType : EMBEDDED PDV'
6091 t[0] = EmbeddedPDVType()
6093 # 34 Notation for the external type -------------------------------------------
6096 def p_ExternalType (t):
6097 'ExternalType : EXTERNAL'
6098 t[0] = ExternalType()
6100 # 36 Notation for character string types --------------------------------------
6103 def p_CharacterStringType (t):
6104 '''CharacterStringType : RestrictedCharacterStringType
6105 | UnrestrictedCharacterStringType'''
6109 # 37 Definition of restricted character string types --------------------------
6111 def p_RestrictedCharacterStringType_1 (t):
6112 'RestrictedCharacterStringType : BMPString'
6113 t[0] = BMPStringType ()
6114 def p_RestrictedCharacterStringType_2 (t):
6115 'RestrictedCharacterStringType : GeneralString'
6116 t[0] = GeneralStringType ()
6117 def p_RestrictedCharacterStringType_3 (t):
6118 'RestrictedCharacterStringType : GraphicString'
6119 t[0] = GraphicStringType ()
6120 def p_RestrictedCharacterStringType_4 (t):
6121 'RestrictedCharacterStringType : IA5String'
6122 t[0] = IA5StringType ()
6123 def p_RestrictedCharacterStringType_5 (t):
6124 'RestrictedCharacterStringType : ISO646String'
6125 t[0] = ISO646StringType ()
6126 def p_RestrictedCharacterStringType_6 (t):
6127 'RestrictedCharacterStringType : NumericString'
6128 t[0] = NumericStringType ()
6129 def p_RestrictedCharacterStringType_7 (t):
6130 'RestrictedCharacterStringType : PrintableString'
6131 t[0] = PrintableStringType ()
6132 def p_RestrictedCharacterStringType_8 (t):
6133 'RestrictedCharacterStringType : TeletexString'
6134 t[0] = TeletexStringType ()
6135 def p_RestrictedCharacterStringType_9 (t):
6136 'RestrictedCharacterStringType : T61String'
6137 t[0] = T61StringType ()
6138 def p_RestrictedCharacterStringType_10 (t):
6139 'RestrictedCharacterStringType : UniversalString'
6140 t[0] = UniversalStringType ()
6141 def p_RestrictedCharacterStringType_11 (t):
6142 'RestrictedCharacterStringType : UTF8String'
6143 t[0] = UTF8StringType ()
6144 def p_RestrictedCharacterStringType_12 (t):
6145 'RestrictedCharacterStringType : VideotexString'
6146 t[0] = VideotexStringType ()
6147 def p_RestrictedCharacterStringType_13 (t):
6148 'RestrictedCharacterStringType : VisibleString'
6149 t[0] = VisibleStringType ()
6152 # 40 Definition of unrestricted character string types ------------------------
6155 def p_UnrestrictedCharacterStringType (t):
6156 'UnrestrictedCharacterStringType : CHARACTER STRING'
6157 t[0] = UnrestrictedCharacterStringType ()
6160 # 41 Notation for types defined in clauses 42 to 44 ---------------------------
6162 # 42 Generalized time ---------------------------------------------------------
6164 def p_UsefulType_1 (t):
6165 'UsefulType : GeneralizedTime'
6166 t[0] = GeneralizedTime()
6168 # 43 Universal time -----------------------------------------------------------
6170 def p_UsefulType_2 (t):
6171 'UsefulType : UTCTime'
6174 # 44 The object descriptor type -----------------------------------------------
6176 def p_UsefulType_3 (t):
6177 'UsefulType : ObjectDescriptor'
6178 t[0] = ObjectDescriptor()
6181 # 45 Constrained types --------------------------------------------------------
6184 def p_ConstrainedType_1 (t):
6185 'ConstrainedType : Type Constraint'
6187 t[0].AddConstraint(t[2])
6189 def p_ConstrainedType_2 (t):
6190 'ConstrainedType : TypeWithConstraint'
6194 def p_TypeWithConstraint_1 (t):
6195 '''TypeWithConstraint : SET Constraint OF Type
6196 | SET SizeConstraint OF Type'''
6197 t[0] = SetOfType (val = t[4], constr = t[2])
6199 def p_TypeWithConstraint_2 (t):
6200 '''TypeWithConstraint : SEQUENCE Constraint OF Type
6201 | SEQUENCE SizeConstraint OF Type'''
6202 t[0] = SequenceOfType (val = t[4], constr = t[2])
6204 def p_TypeWithConstraint_3 (t):
6205 '''TypeWithConstraint : SET Constraint OF NamedType
6206 | SET SizeConstraint OF NamedType'''
6207 t[0] = SetOfType (val = t[4], constr = t[2])
6209 def p_TypeWithConstraint_4 (t):
6210 '''TypeWithConstraint : SEQUENCE Constraint OF NamedType
6211 | SEQUENCE SizeConstraint OF NamedType'''
6212 t[0] = SequenceOfType (val = t[4], constr = t[2])
6216 def p_Constraint (t):
6217 'Constraint : LPAREN ConstraintSpec ExceptionSpec RPAREN'
6220 def p_ConstraintSpec (t):
6221 '''ConstraintSpec : ElementSetSpecs
6222 | GeneralConstraint'''
6225 # 46 Element set specification ------------------------------------------------
6228 def p_ElementSetSpecs_1 (t):
6229 'ElementSetSpecs : RootElementSetSpec'
6232 def p_ElementSetSpecs_2 (t):
6233 'ElementSetSpecs : RootElementSetSpec COMMA ELLIPSIS'
6237 def p_ElementSetSpecs_3 (t):
6238 'ElementSetSpecs : RootElementSetSpec COMMA ELLIPSIS COMMA AdditionalElementSetSpec'
6242 def p_RootElementSetSpec (t):
6243 'RootElementSetSpec : ElementSetSpec'
6246 def p_AdditionalElementSetSpec (t):
6247 'AdditionalElementSetSpec : ElementSetSpec'
6250 def p_ElementSetSpec (t):
6251 'ElementSetSpec : Unions'
6255 'Unions : Intersections'
6259 'Unions : UElems UnionMark Intersections'
6260 t[0] = Constraint(type = 'Union', subtype = [t[1], t[3]])
6266 def p_Intersections_1 (t):
6267 'Intersections : IntersectionElements'
6270 def p_Intersections_2 (t):
6271 'Intersections : IElems IntersectionMark IntersectionElements'
6272 t[0] = Constraint(type = 'Intersection', subtype = [t[1], t[3]])
6275 'IElems : Intersections'
6278 def p_IntersectionElements (t):
6279 'IntersectionElements : Elements'
6282 def p_UnionMark (t):
6286 def p_IntersectionMark (t):
6287 '''IntersectionMark : CIRCUMFLEX
6291 def p_Elements_1 (t):
6292 'Elements : SubtypeElements'
6295 def p_Elements_2 (t):
6296 'Elements : LPAREN ElementSetSpec RPAREN'
6299 # 47 Subtype elements ---------------------------------------------------------
6302 def p_SubtypeElements (t):
6303 '''SubtypeElements : SingleValue
6309 | InnerTypeConstraints
6310 | PatternConstraint'''
6315 def p_SingleValue (t):
6316 'SingleValue : Value'
6317 t[0] = Constraint(type = 'SingleValue', subtype = t[1])
6319 # 47.3 Contained subtype
6321 def p_ContainedSubtype (t):
6322 'ContainedSubtype : Includes Type'
6323 t[0] = Constraint(type = 'ContainedSubtype', subtype = t[2])
6326 '''Includes : INCLUDES
6331 def p_ValueRange (t):
6332 'ValueRange : LowerEndpoint RANGE UpperEndpoint'
6333 t[0] = Constraint(type = 'ValueRange', subtype = [t[1], t[3]])
6336 def p_LowerEndpoint_1 (t):
6337 'LowerEndpoint : LowerEndValue'
6340 def p_LowerEndpoint_2 (t):
6341 'LowerEndpoint : LowerEndValue LT'
6342 t[0] = t[1] # but not inclusive range
6344 def p_UpperEndpoint_1 (t):
6345 'UpperEndpoint : UpperEndValue'
6348 def p_UpperEndpoint_2 (t):
6349 'UpperEndpoint : LT UpperEndValue'
6350 t[0] = t[1] # but not inclusive range
6353 def p_LowerEndValue (t):
6354 '''LowerEndValue : Value
6358 def p_UpperEndValue (t):
6359 '''UpperEndValue : Value
6363 # 47.5 Size constraint
6365 def p_SizeConstraint (t):
6366 'SizeConstraint : SIZE Constraint'
6367 t[0] = Constraint (type = 'Size', subtype = t[2])
6369 # 47.6 Type constraint
6371 def p_TypeConstraint (t):
6372 'TypeConstraint : Type'
6373 t[0] = Constraint (type = 'Type', subtype = t[1])
6375 # 47.7 Permitted alphabet
6377 def p_PermittedAlphabet (t):
6378 'PermittedAlphabet : FROM Constraint'
6379 t[0] = Constraint (type = 'From', subtype = t[2])
6381 # 47.8 Inner subtyping
6383 def p_InnerTypeConstraints (t):
6384 '''InnerTypeConstraints : WITH COMPONENT SingleTypeConstraint
6385 | WITH COMPONENTS MultipleTypeConstraints'''
6386 pass # ignore PER invisible constraint
6389 def p_SingleTypeConstraint (t):
6390 'SingleTypeConstraint : Constraint'
6394 def p_MultipleTypeConstraints (t):
6395 '''MultipleTypeConstraints : FullSpecification
6396 | PartialSpecification'''
6399 def p_FullSpecification (t):
6400 'FullSpecification : LBRACE TypeConstraints RBRACE'
6403 def p_PartialSpecification (t):
6404 'PartialSpecification : LBRACE ELLIPSIS COMMA TypeConstraints RBRACE'
6407 def p_TypeConstraints_1 (t):
6408 'TypeConstraints : named_constraint'
6411 def p_TypeConstraints_2 (t):
6412 'TypeConstraints : TypeConstraints COMMA named_constraint'
6413 t[0] = t[1] + [t[3]]
6415 def p_named_constraint_1 (t):
6416 'named_constraint : identifier constraint'
6417 return Node ('named_constraint', ident = t[1], constr = t[2])
6419 def p_named_constraint_2 (t):
6420 'named_constraint : constraint'
6421 return Node ('named_constraint', constr = t[1])
6423 def p_constraint (t):
6424 'constraint : value_constraint presence_constraint'
6425 t[0] = Node ('constraint', value = t[1], presence = t[2])
6427 def p_value_constraint_1 (t):
6428 'value_constraint : Constraint'
6431 def p_value_constraint_2 (t):
6432 'value_constraint : '
6435 def p_presence_constraint_1 (t):
6436 '''presence_constraint : PRESENT
6441 def p_presence_constraint_2 (t):
6442 '''presence_constraint : '''
6445 # 47.9 Pattern constraint
6447 def p_PatternConstraint (t):
6448 'PatternConstraint : PATTERN Value'
6449 t[0] = Constraint (type = 'Pattern', subtype = t[2])
6451 # 49 The exception identifier
6454 def p_ExceptionSpec_1 (t):
6455 'ExceptionSpec : EXCLAMATION ExceptionIdentification'
6458 def p_ExceptionSpec_2 (t):
6462 def p_ExceptionIdentification (t):
6463 '''ExceptionIdentification : SignedNumber
6465 | Type COLON Value '''
6468 # /*-----------------------------------------------------------------------*/
6469 # /* Value Notation Productions */
6470 # /*-----------------------------------------------------------------------*/
6474 def p_binary_string (t):
6475 'binary_string : BSTRING'
6476 t[0] = BStringValue(val = t[1])
6478 def p_hex_string (t):
6479 'hex_string : HSTRING'
6480 t[0] = HStringValue(val = t[1])
6482 def p_char_string (t):
6483 'char_string : QSTRING'
6491 #--- ITU-T Recommendation X.681 -----------------------------------------------
6493 # 7 ASN.1 lexical items -------------------------------------------------------
6495 # 7.1 Information object class references
6497 def p_objectclassreference (t):
6498 'objectclassreference : CLASS_IDENT'
6499 t[0] = Class_Ref(val=t[1])
6501 # 7.2 Information object references
6503 def p_objectreference (t):
6504 'objectreference : LCASE_IDENT'
6507 # 7.3 Information object set references
6509 #def p_objectsetreference (t):
6510 # 'objectsetreference : UCASE_IDENT'
6513 # 7.4 Type field references
6514 # ucasefieldreference
6515 # 7.5 Value field references
6516 # lcasefieldreference
6517 # 7.6 Value set field references
6518 # ucasefieldreference
6519 # 7.7 Object field references
6520 # lcasefieldreference
6521 # 7.8 Object set field references
6522 # ucasefieldreference
6524 def p_ucasefieldreference (t):
6525 'ucasefieldreference : AMPERSAND UCASE_IDENT'
6528 def p_lcasefieldreference (t):
6529 'lcasefieldreference : AMPERSAND LCASE_IDENT'
6532 # 8 Referencing definitions
6535 def p_DefinedObjectClass (t):
6536 '''DefinedObjectClass : objectclassreference
6537 | UsefulObjectClassReference'''
6540 obj_class = t[0].val
6542 def p_DefinedObject (t):
6543 '''DefinedObject : objectreference'''
6547 def p_UsefulObjectClassReference (t):
6548 '''UsefulObjectClassReference : TYPE_IDENTIFIER
6549 | ABSTRACT_SYNTAX'''
6550 t[0] = Class_Ref(val=t[1])
6552 # 9 Information object class definition and assignment
6555 def p_ObjectClassAssignment (t):
6556 '''ObjectClassAssignment : CLASS_IDENT ASSIGNMENT ObjectClass
6557 | UCASE_IDENT ASSIGNMENT ObjectClass'''
6560 if isinstance(t[0], ObjectClassDefn):
6564 def p_ObjectClass (t):
6565 '''ObjectClass : DefinedObjectClass
6566 | ObjectClassDefn'''
6570 def p_ObjectClassDefn (t):
6571 '''ObjectClassDefn : CLASS LBRACE FieldSpecs RBRACE
6572 | CLASS LBRACE FieldSpecs RBRACE WithSyntaxSpec'''
6573 t[0] = ObjectClassDefn(fields = t[3])
6575 def p_FieldSpecs_1 (t):
6576 'FieldSpecs : FieldSpec'
6579 def p_FieldSpecs_2 (t):
6580 'FieldSpecs : FieldSpecs COMMA FieldSpec'
6581 t[0] = t[1] + [t[3]]
6583 def p_WithSyntaxSpec (t):
6584 'WithSyntaxSpec : WITH SYNTAX lbraceignore rbraceignore'
6588 def p_FieldSpec (t):
6589 '''FieldSpec : TypeFieldSpec
6590 | FixedTypeValueFieldSpec
6591 | FixedTypeValueSetFieldSpec
6593 | ObjectSetFieldSpec '''
6597 def p_TypeFieldSpec (t):
6598 '''TypeFieldSpec : ucasefieldreference
6599 | ucasefieldreference TypeOptionalitySpec '''
6600 t[0] = TypeFieldSpec()
6603 def p_TypeOptionalitySpec_1 (t):
6604 'TypeOptionalitySpec ::= OPTIONAL'
6607 def p_TypeOptionalitySpec_2 (t):
6608 'TypeOptionalitySpec ::= DEFAULT Type'
6612 def p_FixedTypeValueFieldSpec (t):
6613 '''FixedTypeValueFieldSpec : lcasefieldreference Type
6614 | lcasefieldreference Type UNIQUE
6615 | lcasefieldreference Type ValueOptionalitySpec
6616 | lcasefieldreference Type UNIQUE ValueOptionalitySpec '''
6617 t[0] = FixedTypeValueFieldSpec(typ = t[2])
6620 def p_ValueOptionalitySpec_1 (t):
6621 'ValueOptionalitySpec ::= OPTIONAL'
6624 def p_ValueOptionalitySpec_2 (t):
6625 'ValueOptionalitySpec ::= DEFAULT Value'
6629 def p_FixedTypeValueSetFieldSpec (t):
6630 '''FixedTypeValueSetFieldSpec : ucasefieldreference Type
6631 | ucasefieldreference Type ValueSetOptionalitySpec '''
6632 t[0] = FixedTypeValueSetFieldSpec()
6635 def p_ValueSetOptionalitySpec_1 (t):
6636 'ValueSetOptionalitySpec ::= OPTIONAL'
6639 def p_ValueSetOptionalitySpec_2 (t):
6640 'ValueSetOptionalitySpec ::= DEFAULT ValueSet'
6644 def p_ObjectFieldSpec (t):
6645 '''ObjectFieldSpec : lcasefieldreference DefinedObjectClass
6646 | lcasefieldreference DefinedObjectClass ObjectOptionalitySpec '''
6647 t[0] = ObjectFieldSpec(cls=t[2])
6652 def p_ObjectOptionalitySpec_1 (t):
6653 'ObjectOptionalitySpec ::= OPTIONAL'
6656 def p_ObjectOptionalitySpec_2 (t):
6657 'ObjectOptionalitySpec ::= DEFAULT Object'
6661 def p_ObjectSetFieldSpec (t):
6662 '''ObjectSetFieldSpec : ucasefieldreference DefinedObjectClass
6663 | ucasefieldreference DefinedObjectClass ObjectSetOptionalitySpec '''
6664 t[0] = ObjectSetFieldSpec(cls=t[2])
6667 def p_ObjectSetOptionalitySpec_1 (t):
6668 'ObjectSetOptionalitySpec ::= OPTIONAL'
6671 def p_ObjectSetOptionalitySpec_2 (t):
6672 'ObjectSetOptionalitySpec ::= DEFAULT ObjectSet'
6676 def p_PrimitiveFieldName (t):
6677 '''PrimitiveFieldName : ucasefieldreference
6678 | lcasefieldreference '''
6682 def p_FieldName_1 (t):
6683 'FieldName : PrimitiveFieldName'
6686 def p_FieldName_2 (t):
6687 'FieldName : FieldName DOT PrimitiveFieldName'
6688 t[0] = t[1] + '.' + t[3]
6690 # 11 Information object definition and assignment
6693 def p_ObjectAssignment (t):
6694 'ObjectAssignment : objectreference DefinedObjectClass ASSIGNMENT Object'
6695 t[0] = ObjectAssignment (ident = t[1], cls=t[2].val, val=t[4])
6701 '''Object : DefinedObject
6703 | ParameterizedObject'''
6707 def p_ObjectDefn (t):
6708 'ObjectDefn : lbraceobject bodyobject rbraceobject'
6711 # {...} block of object definition
6712 def p_lbraceobject(t):
6713 'lbraceobject : braceobjectbegin LBRACE'
6716 def p_braceobjectbegin(t):
6717 'braceobjectbegin : '
6720 if set_class_syntax(obj_class):
6724 state = 'braceignore'
6725 lexer.push_state(state)
6727 def p_rbraceobject(t):
6728 'rbraceobject : braceobjectend RBRACE'
6731 def p_braceobjectend(t):
6735 set_class_syntax(None)
6737 def p_bodyobject_1 (t):
6741 def p_bodyobject_2 (t):
6742 'bodyobject : cls_syntax_list'
6745 def p_cls_syntax_list_1 (t):
6746 'cls_syntax_list : cls_syntax_list cls_syntax'
6750 def p_cls_syntax_list_2 (t):
6751 'cls_syntax_list : cls_syntax'
6755 def p_cls_syntax_1 (t):
6756 'cls_syntax : Type IDENTIFIED BY Value'
6757 t[0] = { get_class_fieled(' ') : t[1], get_class_fieled(' '.join((t[2], t[3]))) : t[4] }
6759 def p_cls_syntax_2 (t):
6760 'cls_syntax : HAS PROPERTY Value'
6761 t[0] = { get_class_fieled(' '.join(t[1:-1])) : t[-1:][0] }
6764 def p_cls_syntax_3 (t):
6765 '''cls_syntax : ERRORS ObjectSet
6767 | RETURN RESULT BooleanValue
6768 | SYNCHRONOUS BooleanValue
6769 | INVOKE PRIORITY Value
6770 | RESULT_PRIORITY Value
6772 | ALWAYS RESPONDS BooleanValue
6773 | IDEMPOTENT BooleanValue '''
6774 t[0] = { get_class_fieled(' '.join(t[1:-1])) : t[-1:][0] }
6776 def p_cls_syntax_4 (t):
6777 '''cls_syntax : ARGUMENT Type
6781 t[0] = { get_class_fieled(t[1]) : t[2] }
6783 def p_cls_syntax_5 (t):
6784 '''cls_syntax : ARGUMENT Type OPTIONAL BooleanValue
6785 | RESULT Type OPTIONAL BooleanValue
6786 | PARAMETER Type OPTIONAL BooleanValue '''
6787 t[0] = { get_class_fieled(t[1]) : t[2], get_class_fieled(' '.join((t[1], t[3]))) : t[4] }
6789 # 12 Information object set definition and assignment
6792 def p_ObjectSetAssignment (t):
6793 'ObjectSetAssignment : UCASE_IDENT CLASS_IDENT ASSIGNMENT ObjectSet'
6794 t[0] = Node('ObjectSetAssignment', name=t[1], cls=t[2], val=t[4])
6797 def p_ObjectSet (t):
6798 'ObjectSet : lbraceignore rbraceignore'
6801 # 14 Notation for the object class field type ---------------------------------
6804 def p_ObjectClassFieldType (t):
6805 'ObjectClassFieldType : DefinedObjectClass DOT FieldName'
6806 t[0] = get_type_from_class(t[1], t[3])
6809 def p_ObjectClassFieldValue (t):
6810 '''ObjectClassFieldValue : OpenTypeFieldVal'''
6813 def p_OpenTypeFieldVal (t):
6814 '''OpenTypeFieldVal : Type COLON Value
6815 | NullType COLON NullValue'''
6819 # 15 Information from objects -------------------------------------------------
6823 def p_ValueFromObject (t):
6824 'ValueFromObject : LCASE_IDENT DOT FieldName'
6825 t[0] = t[1] + '.' + t[3]
6828 # Annex C - The instance-of type ----------------------------------------------
6831 def p_InstanceOfType (t):
6832 'InstanceOfType : INSTANCE OF DefinedObjectClass'
6833 t[0] = InstanceOfType()
6838 useful_object_class_types = {
6840 'TYPE-IDENTIFIER.&id' : lambda : ObjectIdentifierType(),
6841 'TYPE-IDENTIFIER.&Type' : lambda : OpenType(),
6843 'ABSTRACT-SYNTAX.&id' : lambda : ObjectIdentifierType(),
6844 'ABSTRACT-SYNTAX.&Type' : lambda : OpenType(),
6845 'ABSTRACT-SYNTAX.&property' : lambda : BitStringType(),
6848 object_class_types = { }
6850 object_class_typerefs = { }
6852 object_class_classrefs = { }
6854 class_types_creator = {
6855 'BooleanType' : lambda : BooleanType(),
6856 'IntegerType' : lambda : IntegerType(),
6857 'ObjectIdentifierType' : lambda : ObjectIdentifierType(),
6858 'OpenType' : lambda : OpenType(),
6864 'TYPE-IDENTIFIER' : {
6866 'IDENTIFIED' : 'IDENTIFIED',
6868 'IDENTIFIED BY' : '&id',
6870 'ABSTRACT-SYNTAX' : {
6872 'IDENTIFIED' : 'IDENTIFIED',
6874 'IDENTIFIED BY' : '&id',
6876 'PROPERTY' : 'PROPERTY',
6877 'HAS PROPERTY' : '&property',
6881 class_syntaxes_enabled = {
6882 'TYPE-IDENTIFIER' : True,
6883 'ABSTRACT-SYNTAX' : True,
6887 'TYPE-IDENTIFIER' : x681_syntaxes['TYPE-IDENTIFIER'],
6888 'ABSTRACT-SYNTAX' : x681_syntaxes['ABSTRACT-SYNTAX'],
6891 class_current_syntax = None
6893 def get_syntax_tokens(syntaxes):
6895 for s in (syntaxes):
6896 for k in (syntaxes[s].keys()):
6899 tokens[k] = tokens[k].replace('-', '_')
6900 return tokens.values()
6902 tokens = tokens + get_syntax_tokens(x681_syntaxes)
6904 def set_class_syntax(syntax):
6905 global class_syntaxes_enabled
6906 global class_current_syntax
6907 #print "set_class_syntax", syntax, class_current_syntax
6908 if class_syntaxes_enabled.get(syntax, False):
6909 class_current_syntax = syntax
6912 class_current_syntax = None
6915 def is_class_syntax(name):
6916 global class_syntaxes
6917 global class_current_syntax
6918 #print "is_class_syntax", name, class_current_syntax
6919 if not class_current_syntax:
6921 return class_syntaxes[class_current_syntax].has_key(name)
6923 def get_class_fieled(name):
6924 if not class_current_syntax:
6926 return class_syntaxes[class_current_syntax][name]
6928 def is_class_ident(name):
6929 return class_names.has_key(name)
6931 def add_class_ident(name):
6932 class_names[name] = name
6934 def get_type_from_class(cls, fld):
6935 flds = fld.split('.')
6936 if (isinstance(cls, Class_Ref)):
6937 key = cls.val + '.' + flds[0]
6939 key = cls + '.' + flds[0]
6941 if object_class_classrefs.has_key(key):
6942 return get_type_from_class(object_class_classrefs[key], '.'.join(flds[1:]))
6944 if object_class_typerefs.has_key(key):
6945 return Type_Ref(val=object_class_typerefs[key])
6947 creator = lambda : AnyType()
6948 creator = useful_object_class_types.get(key, creator)
6949 creator = object_class_types.get(key, creator)
6952 def set_type_to_class(cls, fld, pars):
6953 key = cls + '.' + fld
6954 typename = 'OpenType'
6958 pars.append(typename)
6961 if (isinstance(pars[1], Class_Ref)):
6962 pars[1] = pars[1].val
6966 if object_class_types.has_key(key):
6967 msg = object_class_types[key]().type
6968 if object_class_typerefs.has_key(key):
6969 msg = "TypeReference " + object_class_typerefs[key]
6970 if object_class_classrefs.has_key(key):
6971 msg = "ClassReference " + object_class_classrefs[key]
6973 if msg == ' '.join(pars):
6977 msg0 = "Can not define CLASS field %s as '%s'\n" % (key, ' '.join(pars))
6978 msg1 = "Already defined as '%s'" % (msg)
6981 if (typename == 'ClassReference'):
6982 if not typeref: return False
6983 object_class_classrefs[key] = typeref
6986 if (typename == 'TypeReference'):
6987 if not typeref: return False
6988 object_class_typerefs[key] = typeref
6991 creator = class_types_creator.get(typename)
6993 object_class_types[key] = creator
6998 #--- ITU-T Recommendation X.682 -----------------------------------------------
7000 # 8 General constraint specification ------------------------------------------
7003 def p_GeneralConstraint (t):
7004 '''GeneralConstraint : UserDefinedConstraint
7006 | ContentsConstraint'''
7009 # 9 User-defined constraints --------------------------------------------------
7012 def p_UserDefinedConstraint (t):
7013 'UserDefinedConstraint : CONSTRAINED BY LBRACE UserDefinedConstraintParameterList RBRACE'
7014 t[0] = Constraint(type = 'UserDefined', subtype = t[4])
7016 def p_UserDefinedConstraintParameterList_1 (t):
7017 'UserDefinedConstraintParameterList : '
7020 def p_UserDefinedConstraintParameterList_2 (t):
7021 'UserDefinedConstraintParameterList : UserDefinedConstraintParameter'
7024 def p_UserDefinedConstraintParameterList_3 (t):
7025 'UserDefinedConstraintParameterList : UserDefinedConstraintParameterList COMMA UserDefinedConstraintParameter'
7026 t[0] = t[1] + [t[3]]
7029 def p_UserDefinedConstraintParameter (t):
7030 'UserDefinedConstraintParameter : Type'
7033 # 10 Table constraints, including component relation constraints --------------
7036 def p_TableConstraint (t):
7037 '''TableConstraint : SimpleTableConstraint
7038 | ComponentRelationConstraint'''
7039 t[0] = Constraint(type = 'Table', subtype = t[1])
7041 def p_SimpleTableConstraint (t):
7042 'SimpleTableConstraint : LBRACE UCASE_IDENT RBRACE'
7046 def p_ComponentRelationConstraint (t):
7047 'ComponentRelationConstraint : LBRACE UCASE_IDENT RBRACE LBRACE AtNotations RBRACE'
7048 t[0] = t[2] + str(t[5])
7050 def p_AtNotations_1 (t):
7051 'AtNotations : AtNotation'
7054 def p_AtNotations_2 (t):
7055 'AtNotations : AtNotations COMMA AtNotation'
7056 t[0] = t[1] + [t[3]]
7058 def p_AtNotation_1 (t):
7059 'AtNotation : AT ComponentIdList'
7062 def p_AtNotation_2 (t):
7063 'AtNotation : AT DOT Level ComponentIdList'
7064 t[0] = '@.' + t[3] + t[4]
7074 def p_ComponentIdList_1 (t):
7075 'ComponentIdList : LCASE_IDENT'
7078 def p_ComponentIdList_2 (t):
7079 'ComponentIdList : ComponentIdList DOT LCASE_IDENT'
7080 t[0] = t[1] + '.' + t[3]
7082 # 11 Contents constraints -----------------------------------------------------
7085 def p_ContentsConstraint (t):
7086 'ContentsConstraint : CONTAINING type_ref'
7087 t[0] = Constraint(type = 'Contents', subtype = t[2])
7090 #--- ITU-T Recommendation X.683 -----------------------------------------------
7092 # 8 Parameterized assignments -------------------------------------------------
7095 def p_ParameterizedAssignment (t):
7096 '''ParameterizedAssignment : ParameterizedTypeAssignment
7097 | ParameterizedObjectAssignment
7098 | ParameterizedObjectSetAssignment'''
7102 def p_ParameterizedTypeAssignment (t):
7103 'ParameterizedTypeAssignment : UCASE_IDENT ParameterList ASSIGNMENT Type'
7105 t[0].SetName(t[1]) # t[0].SetName(t[1] + 'xxx')
7107 def p_ParameterizedObjectAssignment (t):
7108 'ParameterizedObjectAssignment : objectreference ParameterList DefinedObjectClass ASSIGNMENT Object'
7109 t[0] = ObjectAssignment (ident = t[1], cls=t[3].val, val=t[5])
7113 def p_ParameterizedObjectSetAssignment (t):
7114 'ParameterizedObjectSetAssignment : UCASE_IDENT ParameterList DefinedObjectClass ASSIGNMENT ObjectSet'
7115 t[0] = Node('ObjectSetAssignment', name=t[1], cls=t[3].val, val=t[5])
7118 def p_ParameterList (t):
7119 'ParameterList : lbraceignore rbraceignore'
7121 #def p_ParameterList (t):
7122 # 'ParameterList : LBRACE Parameters RBRACE'
7125 #def p_Parameters_1 (t):
7126 # 'Parameters : Parameter'
7129 #def p_Parameters_2 (t):
7130 # 'Parameters : Parameters COMMA Parameter'
7131 # t[0] = t[1] + [t[3]]
7133 #def p_Parameter_1 (t):
7134 # 'Parameter : Type COLON Reference'
7135 # t[0] = [t[1], t[3]]
7137 #def p_Parameter_2 (t):
7138 # 'Parameter : Reference'
7142 # 9 Referencing parameterized definitions -------------------------------------
7145 def p_ParameterizedReference (t):
7146 'ParameterizedReference : Reference LBRACE RBRACE'
7151 def p_ParameterizedType (t):
7152 'ParameterizedType : type_ref ActualParameterList'
7157 def p_ParameterizedObject (t):
7158 'ParameterizedObject : DefinedObject ActualParameterList'
7163 def p_ActualParameterList (t):
7164 'ActualParameterList : lbraceignore rbraceignore'
7166 #def p_ActualParameterList (t):
7167 # 'ActualParameterList : LBRACE ActualParameters RBRACE'
7170 #def p_ActualParameters_1 (t):
7171 # 'ActualParameters : ActualParameter'
7174 #def p_ActualParameters_2 (t):
7175 # 'ActualParameters : ActualParameters COMMA ActualParameter'
7176 # t[0] = t[1] + [t[3]]
7178 #def p_ActualParameter (t):
7179 # '''ActualParameter : Type
7184 #--- ITU-T Recommendation X.880 -----------------------------------------------
7188 '&ArgumentType' : [],
7189 '&argumentTypeOptional' : [ 'BooleanType' ],
7190 '&returnResult' : [ 'BooleanType' ],
7192 '&resultTypeOptional' : [ 'BooleanType' ],
7193 '&Errors' : [ 'ClassReference', 'ERROR' ],
7194 '&Linked' : [ 'ClassReference', 'OPERATION' ],
7195 '&synchronous' : [ 'BooleanType' ],
7196 '&idempotent' : [ 'BooleanType' ],
7197 '&alwaysReturns' : [ 'BooleanType' ],
7198 # '&InvokePriority' #UNSUPPORTED_FixedTypeValueSetFieldSpec
7199 # '&ResultPriority' #UNSUPPORTED_FixedTypeValueSetFieldSpec
7200 '&operationCode' : [ 'TypeReference', 'Code' ],
7203 '&ParameterType' : [],
7204 '¶meterTypeOptional' : [ 'BooleanType' ],
7205 # '&ErrorPriority' #UNSUPPORTED_FixedTypeValueSetFieldSpec
7206 '&errorCode' : [ 'TypeReference', 'Code' ],
7208 'OPERATION-PACKAGE' : {
7210 'CONNECTION-PACKAGE' : {
7214 'ROS-OBJECT-CLASS' : {
7220 'ARGUMENT' : '&ArgumentType',
7221 'ARGUMENT OPTIONAL' : '&argumentTypeOptional',
7222 'RESULT' : '&ResultType',
7223 'RESULT OPTIONAL' : '&resultTypeOptional',
7224 'RETURN' : 'RETURN',
7225 'RETURN RESULT' : '&returnResult',
7226 'ERRORS' : '&Errors',
7227 'LINKED' : '&Linked',
7228 'SYNCHRONOUS' : '&synchronous',
7229 'IDEMPOTENT' : '&idempotent',
7230 'ALWAYS' : 'ALWAYS',
7231 'RESPONDS' : 'RESPONDS',
7232 'ALWAYS RESPONDS' : '&alwaysReturns',
7233 'INVOKE' : 'INVOKE',
7234 'PRIORITY' : 'PRIORITY',
7235 'INVOKE PRIORITY' : '&InvokePriority',
7236 'RESULT-PRIORITY': '&ResultPriority',
7237 'CODE' : '&operationCode',
7240 'PARAMETER' : '&ParameterType',
7241 'PARAMETER OPTIONAL' : '¶meterTypeOptional',
7242 'PRIORITY' : '&ErrorPriority',
7243 'CODE' : '&errorCode',
7245 # 'OPERATION-PACKAGE' : {
7247 # 'CONNECTION-PACKAGE' : {
7251 # 'ROS-OBJECT-CLASS' : {
7255 def x880_import(name):
7256 if x880_syntaxes.has_key(name):
7257 class_syntaxes_enabled[name] = True
7258 class_syntaxes[name] = x880_syntaxes[name]
7259 if x880_classes.has_key(name):
7260 add_class_ident(name)
7261 for f in (x880_classes[name].keys()):
7262 set_type_to_class(name, f, x880_classes[name][f])
7264 tokens = tokens + get_syntax_tokens(x880_syntaxes)
7267 #def p_lbrace_oid(t):
7268 # 'lbrace_oid : brace_oid_begin LBRACE'
7271 #def p_brace_oid_begin(t):
7272 # 'brace_oid_begin : '
7276 #def p_rbrace_oid(t):
7277 # 'rbrace_oid : brace_oid_end RBRACE'
7280 #def p_brace_oid_end(t):
7281 # 'brace_oid_end : '
7285 # {...} block to be ignored
7286 def p_lbraceignore(t):
7287 'lbraceignore : braceignorebegin LBRACE'
7290 def p_braceignorebegin(t):
7291 'braceignorebegin : '
7294 lexer.push_state('braceignore')
7296 def p_rbraceignore(t):
7297 'rbraceignore : braceignoreend RBRACE'
7300 def p_braceignoreend(t):
7307 raise ParseError(t, input_file)
7310 '''pyquote : PYQUOTE'''
7311 t[0] = PyQuote (val = t[1])
7317 token = lexer.token ()
7323 def do_module (ast, defined_dict):
7324 assert (ast.type == 'Module')
7325 ctx = Ctx (defined_dict)
7326 print ast.to_python (ctx)
7327 print ctx.output_assignments ()
7328 print ctx.output_pyquotes ()
7330 def eth_do_module (ast, ectx):
7331 assert (ast.type == 'Module')
7332 if ectx.dbg('s'): print ast.str_depth(0)
7335 def testyacc(s, fn, defined_dict):
7336 ast = yacc.parse(s, debug=0)
7337 time_str = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime())
7338 print """#!/usr/bin/env python
7339 # Auto-generated from %s at %s
7340 from PyZ3950 import asn1""" % (fn, time_str)
7342 eth_do_module (module, defined_dict)
7345 # Wireshark compiler
7348 asn2wrs [-h|?] [-d dbg] [-b] [-p proto] [-c conform_file] [-e] input_file(s) ...
7350 -b : BER (default is PER)
7351 -u : unaligned (default is aligned)
7352 -p proto : protocol name (implies -S)
7353 default is module-name from input_file (renamed by #.MODULE if present)
7354 -F : create 'field functions'
7355 -T : tagged type support (experimental)
7356 -o name : output files name core (default is <proto>)
7357 -O dir : output directory
7358 -c conform_file : conformation file
7359 -I path : path for conformance file includes
7360 -e : create conformation file for exported types
7361 -S : single output for multiple modules
7362 -s template : single file output (template is input file without .c/.h extension)
7363 -k : keep intermediate files though single file output is used
7364 -L : suppress #line directive from .cnf file
7365 input_file(s) : input ASN.1 file(s)
7367 -d dbg : debug output, dbg = [l][y][p][s][a][t][c][m][o]
7371 s - internal ASN.1 structure
7372 a - list of assignments
7374 c - conformance values
7375 m - list of compiled modules with dependency
7376 o - list of output files
7383 print "ASN.1 to Wireshark dissector compiler";
7385 opts, args = getopt.getopt(sys.argv[1:], "h?d:buXp:FTo:O:c:I:eSs:kL");
7386 except getopt.GetoptError:
7387 eth_usage(); sys.exit(2)
7389 eth_usage(); sys.exit(2)
7394 ectx = EthCtx(conform, output)
7395 ectx.encoding = 'per'
7396 ectx.proto_opt = None
7398 ectx.tag_opt = False
7399 ectx.outnm_opt = None
7404 ectx.merge_modules = False
7405 ectx.group_by_prot = False
7406 ectx.conform.last_group = 0
7407 ectx.conform.suppress_line = False;
7408 ectx.output.outnm = None
7409 ectx.output.single_file = None
7411 if o in ("-h", "-?"):
7412 eth_usage(); sys.exit(2)
7416 ectx.conform.include_path.append(a)
7418 # warnings.warn("Command line option -X is obsolete and can be removed")
7421 ectx.conform.read(conf_to_read)
7424 if o in ("-h", "-?", "-c", "-I"):
7425 pass # already processed
7429 ectx.conform.set_opt(o, par, "commandline", 0)
7431 (ld, yd, pd) = (0, 0, 0);
7432 if ectx.dbg('l'): ld = 1
7433 if ectx.dbg('y'): yd = 1
7434 if ectx.dbg('p'): pd = 2
7435 lexer = lex.lex(debug=ld)
7436 yacc.yacc(method='LALR', debug=yd)
7437 g_conform = ectx.conform
7443 ast.extend(yacc.parse(f.read(), lexer=lexer, debug=pd))
7446 if (ectx.merge_modules): # common output for all module
7449 eth_do_module(module, ectx)
7451 ectx.eth_do_output()
7452 elif (ectx.groups()): # group by protocols/group
7455 if (ectx.group_by_prot): # group by protocols
7457 prot = module.get_proto(ectx)
7458 if not pr2gr.has_key(prot):
7459 pr2gr[prot] = len(groups)
7461 groups[pr2gr[prot]].append(module)
7462 else: # group by groups
7467 eth_do_module(module, ectx)
7469 ectx.eth_do_output()
7470 else: # output for each module
7473 eth_do_module(module, ectx)
7475 ectx.eth_do_output()
7481 ectx.conform.dbg_print()
7482 ectx.conform.unused_report()
7485 ectx.output.dbg_print()
7486 ectx.output.make_single_file()
7492 if len (sys.argv) == 1:
7494 s = raw_input ('Query: ')
7497 testfn (s, 'console', {})
7500 for fn in sys.argv [1:]:
7502 testfn (f.read (), fn, defined_dict)
7507 #--- BODY ---------------------------------------------------------------------
7509 if __name__ == '__main__':
7510 if (os.path.splitext(os.path.basename(sys.argv[0]))[0].lower() in ('asn2wrs', 'asn2eth')):
7515 #------------------------------------------------------------------------------