asn2wrs.py 301 KB
Newer Older
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
1 2 3
#!/usr/bin/env python

#
4
# asn2wrs.py
Tomas Kukosa's avatar
Tomas Kukosa committed
5
# ASN.1 to Wireshark dissector compiler
6
# Copyright 2004 Tomas Kukosa
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
7
#
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, and/or sell copies of the Software, and to permit persons
# to whom the Software is furnished to do so, provided that the above
# copyright notice(s) and this permission notice appear in all copies of
# the Software and that both the above copyright notice(s) and this
# permission notice appear in supporting documentation.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
# OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# Except as contained in this notice, the name of a copyright holder
# shall not be used in advertising or otherwise to promote the sale, use
# or other dealings in this Software without prior written authorization
# of the copyright holder.

Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
33

Tomas Kukosa's avatar
Tomas Kukosa committed
34
"""ASN.1 to Wireshark dissector compiler"""
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
35 36

#
Tomas Kukosa's avatar
Tomas Kukosa committed
37
# Compiler from ASN.1 specification to the Wireshark dissector
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
38 39 40 41 42
#
# Based on ASN.1 to Python compiler from Aaron S. Lav's PyZ3950 package licensed under the X Consortium license
# http://www.pobox.com/~asl2/software/PyZ3950/
# (ASN.1 to Python compiler functionality is broken but not removed, it could be revived if necessary)
#
43
# It requires Dave Beazley's PLY parsing package licensed under the LGPL (tested with version 2.3)
44
# http://www.dabeaz.com/ply/
45 46 47
#
#
# ITU-T Recommendation X.680 (07/2002),
48
#   Information technology - Abstract Syntax Notation One (ASN.1): Specification of basic notation
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
49
#
50
# ITU-T Recommendation X.681 (07/2002),
51 52
#   Information technology - Abstract Syntax Notation One (ASN.1): Information object specification
#
53
# ITU-T Recommendation X.682 (07/2002),
54
#   Information technology - Abstract Syntax Notation One (ASN.1): Constraint specification
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
55
#
56
# ITU-T Recommendation X.683 (07/2002),
57
#   Information technology - Abstract Syntax Notation One (ASN.1): Parameterization of ASN.1 specifications
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
58
#
59
# ITU-T Recommendation X.880 (07/1994),
60 61
#   Information technology - Remote Operations: Concepts, model and notation
#
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
62 63 64

import warnings

Guy Harris's avatar
Guy Harris committed
65 66 67 68 69 70
import re
import sys
import os
import os.path
import time
import getopt
71
import traceback
Guy Harris's avatar
Guy Harris committed
72

73 74
import lex
import yacc
Guy Harris's avatar
Guy Harris committed
75

76 77 78
if sys.version_info[0] < 3:
    from string import maketrans

79

Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
80 81
# OID name -> number conversion table
oid_names = {
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
    '/itu-t' : 0,
    '/itu'   : 0,
    '/ccitt' : 0,
    '/itu-r' : 0,
    '0/recommendation' : 0,
    '0.0/a' : 1,
    '0.0/b' : 2,
    '0.0/c' : 3,
    '0.0/d' : 4,
    '0.0/e' : 5,
    '0.0/f' : 6,
    '0.0/g' : 7,
    '0.0/h' : 8,
    '0.0/i' : 9,
    '0.0/j' : 10,
    '0.0/k' : 11,
    '0.0/l' : 12,
    '0.0/m' : 13,
    '0.0/n' : 14,
    '0.0/o' : 15,
    '0.0/p' : 16,
    '0.0/q' : 17,
    '0.0/r' : 18,
    '0.0/s' : 19,
    '0.0/t' : 20,
    '0.0/tseries' : 20,
    '0.0/u' : 21,
    '0.0/v' : 22,
    '0.0/w' : 23,
    '0.0/x' : 24,
    '0.0/y' : 25,
    '0.0/z' : 26,
    '0/question' : 1,
    '0/administration' : 2,
    '0/network-operator' : 3,
    '0/identified-organization' : 4,
    '0/r-recommendation' : 5,
    '0/data' : 9,
    '/iso' : 1,
    '1/standard' : 0,
    '1/registration-authority' : 1,
    '1/member-body' : 2,
    '1/identified-organization' : 3,
    '/joint-iso-itu-t' : 2,
    '/joint-iso-ccitt' : 2,
    '2/presentation' : 0,
    '2/asn1' : 1,
    '2/association-control' : 2,
    '2/reliable-transfer' : 3,
    '2/remote-operations' : 4,
    '2/ds' : 5,
    '2/directory' : 5,
    '2/mhs' : 6,
    '2/mhs-motis' : 6,
    '2/ccr' : 7,
    '2/oda' : 8,
    '2/ms' : 9,
    '2/osi-management' : 9,
    '2/transaction-processing' : 10,
    '2/dor' : 11,
    '2/distinguished-object-reference' : 11,
    '2/reference-data-transfe' : 12,
    '2/network-layer' : 13,
    '2/network-layer-management' : 13,
    '2/transport-layer' : 14,
    '2/transport-layer-management' : 14,
    '2/datalink-layer' : 15,
    '2/datalink-layer-managemen' : 15,
    '2/datalink-layer-management-information' : 15,
    '2/country' : 16,
    '2/registration-procedures' : 17,
    '2/registration-procedure' : 17,
    '2/physical-layer' : 18,
    '2/physical-layer-management' : 18,
    '2/mheg' : 19,
    '2/genericULS' : 20,
    '2/generic-upper-layers-security' : 20,
    '2/guls' : 20,
    '2/transport-layer-security-protocol' : 21,
    '2/network-layer-security-protocol' : 22,
    '2/international-organizations' : 23,
    '2/internationalRA' : 23,
    '2/sios' : 24,
    '2/uuid' : 25,
    '2/odp' : 26,
    '2/upu' : 40,
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
168 169
}

170 171 172
ITEM_FIELD_NAME = '_item'
UNTAG_TYPE_NAME = '_untag'

Guy Harris's avatar
Guy Harris committed
173
def asn2c(id):
174
    return id.replace('-', '_').replace('.', '_').replace('&', '_')
Guy Harris's avatar
Guy Harris committed
175

176
input_file = None
177
g_conform = None
178
lexer = None
179
in_oid = False
180 181

class LexError(Exception):
182 183 184 185 186 187 188 189
    def __init__(self, tok, filename=None):
        self.tok = tok
        self.filename = filename
        self.msg =  "Unexpected character %r" % (self.tok.value[0])
        Exception.__init__(self, self.msg)
    def __repr__(self):
        return "%s:%d: %s" % (self.filename, self.tok.lineno, self.msg)
    __str__ = __repr__
190 191 192


class ParseError(Exception):
193 194 195 196 197 198 199 200
    def __init__(self, tok, filename=None):
        self.tok = tok
        self.filename = filename
        self.msg =  "Unexpected token %s(%r)" % (self.tok.type, self.tok.value)
        Exception.__init__(self, self.msg)
    def __repr__(self):
        return "%s:%d: %s" % (self.filename, self.tok.lineno, self.msg)
    __str__ = __repr__
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
201

202

203
class DuplicateError(Exception):
204 205 206 207 208 209 210 211
    def __init__(self, type, ident):
        self.type = type
        self.ident = ident
        self.msg =  "Duplicate %s for %s" % (self.type, self.ident)
        Exception.__init__(self, self.msg)
    def __repr__(self):
        return self.msg
    __str__ = __repr__
212 213

class CompError(Exception):
214 215 216 217 218 219
    def __init__(self, msg):
        self.msg =  msg
        Exception.__init__(self, self.msg)
    def __repr__(self):
        return self.msg
    __str__ = __repr__
220 221


222 223 224 225
states = (
  ('braceignore','exclusive'),
)

226 227 228 229
precedence = (
  ('left', 'UNION', 'BAR'),
  ('left', 'INTERSECTION', 'CIRCUMFLEX'),
)
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
230 231 232
# 11 ASN.1 lexical items

static_tokens = {
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
    r'::='    : 'ASSIGNMENT',  # 11.16 Assignment lexical item
    r'\.\.'   : 'RANGE',       # 11.17 Range separator
    r'\.\.\.' : 'ELLIPSIS',    # 11.18 Ellipsis
    r'\[\['   : 'LVERBRACK',   # 11.19 Left version brackets
    r'\]\]'   : 'RVERBRACK',   # 11.20 Right version brackets
    # 11.26 Single character lexical items
    r'\{' : 'LBRACE',
    r'\}' : 'RBRACE',
    r'<'  : 'LT',
    #r'>'  : 'GT',
    r','  : 'COMMA',
    r'\.' : 'DOT',
    r'\(' : 'LPAREN',
    r'\)' : 'RPAREN',
    r'\[' : 'LBRACK',
    r'\]' : 'RBRACK',
    r'-'  : 'MINUS',
    r':'  : 'COLON',
    #r'='  : 'EQ',
    #r'"'  : 'QUOTATION',
    #r"'"  : 'APOSTROPHE',
    r';'  : 'SEMICOLON',
    r'@'  : 'AT',
    r'\!' : 'EXCLAMATION',
    r'\^' : 'CIRCUMFLEX',
    r'\&' : 'AMPERSAND',
    r'\|' : 'BAR'
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
260 261 262 263 264 265
}

# 11.27 Reserved words

# all keys in reserved_words must start w/ upper case
reserved_words = {
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
    'ABSENT'      : 'ABSENT',
    'ABSTRACT-SYNTAX' : 'ABSTRACT_SYNTAX',
    'ALL'         : 'ALL',
    'APPLICATION' : 'APPLICATION',
    'AUTOMATIC'   : 'AUTOMATIC',
    'BEGIN'       : 'BEGIN',
    'BIT'         : 'BIT',
    'BOOLEAN'     : 'BOOLEAN',
    'BY'          : 'BY',
    'CHARACTER'   : 'CHARACTER',
    'CHOICE'      : 'CHOICE',
    'CLASS'       : 'CLASS',
    'COMPONENT'   : 'COMPONENT',
    'COMPONENTS'  : 'COMPONENTS',
    'CONSTRAINED' : 'CONSTRAINED',
    'CONTAINING'  : 'CONTAINING',
    'DEFAULT'     : 'DEFAULT',
    'DEFINITIONS' : 'DEFINITIONS',
    'EMBEDDED'    : 'EMBEDDED',
#    'ENCODED'     : 'ENCODED',
    'END'         : 'END',
    'ENUMERATED'  : 'ENUMERATED',
#    'EXCEPT'      : 'EXCEPT',
    'EXPLICIT'    : 'EXPLICIT',
    'EXPORTS'     : 'EXPORTS',
#    'EXTENSIBILITY' : 'EXTENSIBILITY',
    'EXTERNAL'    : 'EXTERNAL',
    'FALSE'       : 'FALSE',
    'FROM'        : 'FROM',
    'GeneralizedTime' : 'GeneralizedTime',
    'IDENTIFIER'  : 'IDENTIFIER',
    'IMPLICIT'    : 'IMPLICIT',
#    'IMPLIED'     : 'IMPLIED',
    'IMPORTS'     : 'IMPORTS',
    'INCLUDES'    : 'INCLUDES',
    'INSTANCE'    : 'INSTANCE',
    'INTEGER'     : 'INTEGER',
    'INTERSECTION' : 'INTERSECTION',
    'MAX'         : 'MAX',
    'MIN'         : 'MIN',
    'MINUS-INFINITY' : 'MINUS_INFINITY',
    'NULL'        : 'NULL',
    'OBJECT'      : 'OBJECT',
    'ObjectDescriptor' : 'ObjectDescriptor',
    'OCTET'       : 'OCTET',
    'OF'          : 'OF',
    'OPTIONAL'    : 'OPTIONAL',
    'PATTERN'     : 'PATTERN',
    'PDV'         : 'PDV',
    'PLUS-INFINITY' : 'PLUS_INFINITY',
    'PRESENT'     : 'PRESENT',
    'PRIVATE'     : 'PRIVATE',
    'REAL'        : 'REAL',
    'RELATIVE-OID' : 'RELATIVE_OID',
    'SEQUENCE'    : 'SEQUENCE',
    'SET'         : 'SET',
    'SIZE'        : 'SIZE',
    'STRING'      : 'STRING',
    'SYNTAX'      : 'SYNTAX',
    'TAGS'        : 'TAGS',
    'TRUE'        : 'TRUE',
    'TYPE-IDENTIFIER' : 'TYPE_IDENTIFIER',
    'UNION'       : 'UNION',
    'UNIQUE'      : 'UNIQUE',
    'UNIVERSAL'   : 'UNIVERSAL',
    'UTCTime'     : 'UTCTime',
    'WITH'        : 'WITH',
333
# X.208 obsolete but still used
334 335
    'ANY'         : 'ANY',
    'DEFINED'     : 'DEFINED',
336
}
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
337

338
for k in list(static_tokens.keys()):
339 340
    if static_tokens [k] == None:
        static_tokens [k] = k
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
341 342 343 344 345 346

StringTypes = ['Numeric', 'Printable', 'IA5', 'BMP', 'Universal', 'UTF8',
               'Teletex', 'T61', 'Videotex', 'Graphic', 'ISO646', 'Visible',
               'General']

for s in StringTypes:
347
    reserved_words[s + 'String'] = s + 'String'
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
348

349 350
tokens = list(static_tokens.values()) \
         + list(reserved_words.values()) \
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
351
         + ['BSTRING', 'HSTRING', 'QSTRING',
352
            'UCASE_IDENT', 'LCASE_IDENT', 'LCASE_IDENT_ASSIGNED', 'CLASS_IDENT',
353
            'REAL_NUMBER', 'NUMBER', 'PYQUOTE']
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
354 355


356 357
cur_mod = __import__ (__name__) # XXX blech!

358
for (k, v) in list(static_tokens.items ()):
359
    cur_mod.__dict__['t_' + v] = k
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
360 361 362 363 364 365 366 367 368 369 370 371 372

# 11.10 Binary strings
def t_BSTRING (t):
    r"'[01]*'B"
    return t

# 11.12 Hexadecimal strings
def t_HSTRING (t):
    r"'[0-9A-Fa-f]*'H"
    return t

def t_QSTRING (t):
    r'"([^"]|"")*"'
373
    return t
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
374 375 376

def t_UCASE_IDENT (t):
    r"[A-Z](-[a-zA-Z0-9]|[a-zA-Z0-9])*" # can't end w/ '-'
377
    if (is_class_ident(t.value)): t.type = 'CLASS_IDENT'
378
    if (is_class_syntax(t.value)): t.type = t.value
379
    t.type = reserved_words.get(t.value, t.type)
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
380 381
    return t

382
lcase_ident_assigned = {}
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
383 384
def t_LCASE_IDENT (t):
    r"[a-z](-[a-zA-Z0-9]|[a-zA-Z0-9])*" # can't end w/ '-'
385
    if (not in_oid and (t.value in lcase_ident_assigned)): t.type = 'LCASE_IDENT_ASSIGNED'
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
386 387
    return t

388 389 390 391 392
# 11.9 Real numbers
def t_REAL_NUMBER (t):
    r"[0-9]+\.[0-9]*(?!\.)"
    return t

Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
393 394 395 396 397 398 399 400 401
# 11.8 Numbers
def t_NUMBER (t):
    r"0|([1-9][0-9]*)"
    return t

# 11.6 Comments
pyquote_str = 'PYQUOTE'
def t_COMMENT(t):
    r"--(-[^\-\n]|[^\-\n])*(--|\n|-\n|$|-$)"
402
    if (t.value.find("\n") >= 0) : t.lexer.lineno += 1
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
403 404 405 406 407 408 409 410 411 412 413
    if t.value[2:2+len (pyquote_str)] == pyquote_str:
        t.value = t.value[2+len(pyquote_str):]
        t.value = t.value.lstrip ()
        t.type = pyquote_str
        return t
    return None

t_ignore = " \t\r"

def t_NEWLINE(t):
    r'\n+'
414
    t.lexer.lineno += t.value.count("\n")
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
415 416

def t_error(t):
417 418
    global input_file
    raise LexError(t, input_file)
419 420 421

# state 'braceignore'

422
def t_braceignore_lbrace(t):
423 424
    r'\{'
    t.lexer.level +=1
425 426

def t_braceignore_rbrace(t):
427 428 429 430 431 432
    r'\}'
    t.lexer.level -=1
    # If closing brace, return token
    if t.lexer.level == 0:
        t.type = 'RBRACE'
        return t
433 434

def t_braceignore_QSTRING (t):
435 436
    r'"([^"]|"")*"'
    t.lexer.lineno += t.value.count("\n")
437 438

def t_braceignore_COMMENT(t):
439 440
    r"--(-[^\-\n]|[^\-\n])*(--|\n|-\n|$|-$)"
    if (t.value.find("\n") >= 0) : t.lexer.lineno += 1
441 442

def t_braceignore_nonspace(t):
443
    r'[^\s\{\}\"-]+|-(?!-)'
444 445 446 447

t_braceignore_ignore = " \t\r"

def t_braceignore_NEWLINE(t):
448 449
    r'\n+'
    t.lexer.lineno += t.value.count("\n")
450 451

def t_braceignore_error(t):
452
    t.lexer.skip(1)
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470

class Ctx:
    def __init__ (self, defined_dict, indent = 0):
        self.tags_def = 'EXPLICIT' # default = explicit
        self.indent_lev = 0
        self.assignments = {}
        self.dependencies = {}
        self.pyquotes = []
        self.defined_dict = defined_dict
        self.name_ctr = 0
    def spaces (self):
        return " " * (4 * self.indent_lev)
    def indent (self):
        self.indent_lev += 1
    def outdent (self):
        self.indent_lev -= 1
        assert (self.indent_lev >= 0)
    def register_assignment (self, ident, val, dependencies):
471
        if ident in self.assignments:
472
            raise DuplicateError("assignment", ident)
473
        if ident in self.defined_dict:
474
            raise Exception("cross-module duplicates for %s" % ident)
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
475 476 477 478 479 480 481 482 483 484 485
        self.defined_dict [ident] = 1
        self.assignments[ident] = val
        self.dependencies [ident] = dependencies
        return ""
    #        return "#%s depends on %s" % (ident, str (dependencies))
    def register_pyquote (self, val):
        self.pyquotes.append (val)
        return ""
    def output_assignments (self):
        already_output = {}
        text_list = []
486
        assign_keys = list(self.assignments.keys())
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
487
        to_output_count = len (assign_keys)
488
        while True:
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
489
            any_output = 0
490 491
            for (ident, val) in list(self.assignments.items ()):
                if ident in already_output:
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
492 493 494
                    continue
                ok = 1
                for d in self.dependencies [ident]:
495 496
                    if ((d not in already_output) and
                        (d in assign_keys)):
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
497 498 499 500 501 502 503 504 505 506 507 508 509
                        ok = 0
                if ok:
                    text_list.append ("%s=%s" % (ident,
                                                self.assignments [ident]))
                    already_output [ident] = 1
                    any_output = 1
                    to_output_count -= 1
                    assert (to_output_count >= 0)
            if not any_output:
                if to_output_count == 0:
                    break
                # OK, we detected a cycle
                cycle_list = []
510 511
                for ident in list(self.assignments.keys ()):
                    if ident not in already_output:
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
512 513
                        depend_list = [d for d in self.dependencies[ident] if d in assign_keys]
                        cycle_list.append ("%s(%s)" % (ident, ",".join (depend_list)))
514

Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
515
                text_list.append ("# Cycle XXX " + ",".join (cycle_list))
516 517
                for (ident, val) in list(self.assignments.items ()):
                    if ident not in already_output:
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
518 519 520 521 522 523 524 525 526 527
                        text_list.append ("%s=%s" % (ident, self.assignments [ident]))
                break

        return "\n".join (text_list)
    def output_pyquotes (self):
        return "\n".join (self.pyquotes)
    def make_new_name (self):
        self.name_ctr += 1
        return "_compiler_generated_name_%d" % (self.name_ctr,)

528
#--- Flags for EXPORT, USER_DEFINED, NO_EMIT, MAKE_ENUM -------------------------------
529 530 531
EF_TYPE    = 0x0001
EF_VALS    = 0x0002
EF_ENUM    = 0x0004
532
EF_WS_DLL  = 0x0010 #  exported from shared library
533 534 535 536
EF_EXTERN  = 0x0020
EF_NO_PROT = 0x0040
EF_NO_TYPE = 0x0080
EF_UCASE   = 0x0100
537
EF_TABLE   = 0x0400
538
EF_DEFINE  = 0x0800
539
EF_MODULE  = 0x1000
540

541 542 543 544
#--- common dependency computation ---
# Input  : list of items
#          dictionary with lists of dependency
#
545
#
546 547 548 549
# Output : list of two outputs:
#          [0] list of items in dependency
#          [1] list of cycle dependency cycles
def dependency_compute(items, dependency, map_fn = lambda t: t, ignore_fn = lambda t: False):
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
    item_ord = []
    item_cyc = []
    x = {}  # already emitted
    #print '# Dependency computation'
    for t in items:
        if map_fn(t) in x:
            #print 'Continue: %s : %s' % (t, (map_fn(t))
            continue
        stack = [t]
        stackx = {t : dependency.get(t, [])[:]}
        #print 'Push: %s : %s' % (t, str(stackx[t]))
        while stack:
            if stackx[stack[-1]]:  # has dependencies
                d = stackx[stack[-1]].pop(0)
                if map_fn(d) in x or ignore_fn(d):
                    continue
                if d in stackx:  # cyclic dependency
                    c = stack[:]
                    c.reverse()
                    c = [d] + c[0:c.index(d)+1]
                    c.reverse()
                    item_cyc.append(c)
                    #print 'Cyclic: %s ' % (' -> '.join(c))
                    continue
                stack.append(d)
                stackx[d] = dependency.get(d, [])[:]
                #print 'Push: %s : %s' % (d, str(stackx[d]))
            else:
                #print 'Pop: %s' % (stack[-1])
                del stackx[stack[-1]]
                e = map_fn(stack.pop())
                if e in x:
                    continue
                #print 'Add: %s' % (e)
                item_ord.append(e)
                x[e] = True
    return (item_ord, item_cyc)
587

588 589 590 591
# Given a filename, return a relative path from the current directory
def relpath(filename):
    return os.path.relpath(filename)

592 593
# Given a filename, return a relative path from epan/dissectors
def rel_dissector_path(filename):
594 595 596
    path_parts = os.path.abspath(filename).split(os.sep)
    while (len(path_parts) > 3 and path_parts[0] != 'asn1'):
        path_parts.pop(0)
597
    path_parts.insert(0, '.')
598
    return '/'.join(path_parts)
599

600

Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
601 602
#--- EthCtx -------------------------------------------------------------------
class EthCtx:
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
    def __init__(self, conform, output, indent = 0):
        self.conform = conform
        self.output = output
        self.conform.ectx = self
        self.output.ectx = self
        self.encoding = 'per'
        self.aligned = False
        self.default_oid_variant = ''
        self.default_opentype_variant = ''
        self.default_containing_variant = '_pdu_new'
        self.default_embedded_pdv_cb = None
        self.default_external_type_cb = None
        self.remove_prefix = None
        self.srcdir = None
        self.emitted_pdu = {}
        self.module = {}
        self.module_ord = []
        self.all_type_attr = {}
        self.all_tags = {}
        self.all_vals = {}

    def encp(self):  # encoding protocol
        encp = self.encoding
        return encp

    # Encoding
    def Per(self): return self.encoding == 'per'
    def Ber(self): return self.encoding == 'ber'
    def Aligned(self): return self.aligned
    def Unaligned(self): return not self.aligned
    def NeedTags(self): return self.tag_opt or self.Ber()
    def NAPI(self): return False  # disable planned features

    def Module(self):  # current module name
        return self.modules[-1][0]

    def groups(self):
        return self.group_by_prot or (self.conform.last_group > 0)

    def dbg(self, d):
        if (self.dbgopt.find(d) >= 0):
            return True
        else:
            return False
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
647

648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
    def value_max(self, a, b):
        if (a == 'MAX') or (b == 'MAX'): return 'MAX';
        if a == 'MIN': return b;
        if b == 'MIN': return a;
        try:
            if (int(a) > int(b)):
                return a
            else:
                return b
        except (ValueError, TypeError):
            pass
        return "MAX((%s),(%s))" % (a, b)

    def value_min(self, a, b):
        if (a == 'MIN') or (b == 'MIN'): return 'MIN';
        if a == 'MAX': return b;
        if b == 'MAX': return a;
        try:
            if (int(a) < int(b)):
                return a
            else:
                return b
        except (ValueError, TypeError):
            pass
        return "MIN((%s),(%s))" % (a, b)

    def value_get_eth(self, val):
        if isinstance(val, Value):
            return val.to_str(self)
        ethname = val
        if val in self.value:
            ethname = self.value[val]['ethname']
        return ethname

    def value_get_val(self, nm):
        val = asn2c(nm)
        if nm in self.value:
            if self.value[nm]['import']:
                v = self.get_val_from_all(nm, self.value[nm]['import'])
                if v is None:
                    msg = 'Need value of imported value identifier %s from %s (%s)' % (nm, self.value[nm]['import'], self.value[nm]['proto'])
                    warnings.warn_explicit(msg, UserWarning, '', 0)
                else:
                    val = v
            else:
                val = self.value[nm]['value']
                if isinstance (val, Value):
                    val = val.to_str(self)
696
        else:
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
            msg = 'Need value of unknown value identifier %s' % (nm)
            warnings.warn_explicit(msg, UserWarning, '', 0)
        return val

    def eth_get_type_attr(self, type):
        #print "eth_get_type_attr(%s)" % (type)
        types = [type]
        while (not self.type[type]['import']):
            val =  self.type[type]['val']
            #print val
            ttype = type
            while (val.type == 'TaggedType'):
                val = val.val
                ttype += '/' + UNTAG_TYPE_NAME
            if (val.type != 'Type_Ref'):
                if (type != ttype):
                    types.append(ttype)
                break
            type = val.val
            types.append(type)
        attr = {}
        #print " ", types
        while len(types):
            t = types.pop()
            if (self.type[t]['import']):
                attr.update(self.type[t]['attr'])
                attr.update(self.eth_get_type_attr_from_all(t, self.type[t]['import']))
            elif (self.type[t]['val'].type == 'SelectionType'):
                val = self.type[t]['val']
                (ftype, display) = val.eth_ftype(self)
                attr.update({ 'TYPE' : ftype, 'DISPLAY' : display,
                              'STRINGS' : val.eth_strings(), 'BITMASK' : '0' });
            else:
                attr.update(self.type[t]['attr'])
                attr.update(self.eth_type[self.type[t]['ethname']]['attr'])
        #print " ", attr
        return attr

    def eth_get_type_attr_from_all(self, type, module):
        attr = {}
        if module in self.all_type_attr and type in self.all_type_attr[module]:
            attr = self.all_type_attr[module][type]
        return attr

    def get_ttag_from_all(self, type, module):
        ttag = None
        if module in self.all_tags and type in self.all_tags[module]:
            ttag = self.all_tags[module][type]
        return ttag

    def get_val_from_all(self, nm, module):
        val = None
        if module in self.all_vals and nm in self.all_vals[module]:
            val = self.all_vals[module][nm]
        return val

    def get_obj_repr(self, ident, flds=[], not_flds=[]):
        def set_type_fn(cls, field, fnfield):
            obj[fnfield + '_fn'] = 'NULL'
            obj[fnfield + '_pdu'] = 'NULL'
            if field in val and isinstance(val[field], Type_Ref):
                p = val[field].eth_type_default_pars(self, '')
                obj[fnfield + '_fn'] = p['TYPE_REF_FN']
                obj[fnfield + '_fn'] = obj[fnfield + '_fn'] % p  # one iteration
                if (self.conform.check_item('PDU', cls + '.' + field)):
                    obj[fnfield + '_pdu'] = 'dissect_' + self.field[val[field].val]['ethname']
            return
        # end of get_type_fn()
        obj = { '_name' : ident, '_ident' : asn2c(ident)}
        obj['_class'] = self.oassign[ident].cls
        obj['_module'] = self.oassign[ident].module
        val = self.oassign[ident].val
        for f in flds:
            if f not in val:
                return None
        for f in not_flds:
            if f in val:
                return None
        for f in list(val.keys()):
            if isinstance(val[f], Node):
                obj[f] = val[f].fld_obj_repr(self)
            else:
                obj[f] = str(val[f])
        if (obj['_class'] == 'TYPE-IDENTIFIER') or (obj['_class'] == 'ABSTRACT-SYNTAX'):
            set_type_fn(obj['_class'], '&Type', '_type')
        if (obj['_class'] == 'OPERATION'):
            set_type_fn(obj['_class'], '&ArgumentType', '_argument')
            set_type_fn(obj['_class'], '&ResultType', '_result')
        if (obj['_class'] == 'ERROR'):
            set_type_fn(obj['_class'], '&ParameterType', '_parameter')
        return obj

    #--- eth_reg_module -----------------------------------------------------------
    def eth_reg_module(self, module):
        #print "eth_reg_module(module='%s')" % (module)
        name = module.get_name()
        self.modules.append([name, module.get_proto(self)])
        if name in self.module:
            raise DuplicateError("module", name)
        self.module[name] = []
        self.module_ord.append(name)

    #--- eth_module_dep_add ------------------------------------------------------------
    def eth_module_dep_add(self, module, dep):
        self.module[module].append(dep)

    #--- eth_exports ------------------------------------------------------------
    def eth_exports(self, exports):
        self.exports_all = False
        if ((len(exports) == 1) and (exports[0] == 'ALL')):
            self.exports_all = True
            return
        for e in (exports):
            if isinstance(e, Type_Ref):
                self.exports.append(e.val)
            elif isinstance(e, Class_Ref):
                self.cexports.append(e.val)
            else:
                self.vexports.append(e)

    #--- eth_reg_assign ---------------------------------------------------------
    def eth_reg_assign(self, ident, val, virt=False):
        #print "eth_reg_assign(ident='%s')" % (ident)
        if ident in self.assign:
            raise DuplicateError("assignment", ident)
        self.assign[ident] = { 'val' : val , 'virt' : virt }
        self.assign_ord.append(ident)
        if  (self.exports_all):
            self.exports.append(ident)

    #--- eth_reg_vassign --------------------------------------------------------
    def eth_reg_vassign(self, vassign):
        ident = vassign.ident
        #print "eth_reg_vassign(ident='%s')" % (ident)
        if ident in self.vassign:
            raise DuplicateError("value assignment", ident)
        self.vassign[ident] = vassign
        self.vassign_ord.append(ident)
        if  (self.exports_all):
            self.vexports.append(ident)

    #--- eth_reg_oassign --------------------------------------------------------
    def eth_reg_oassign(self, oassign):
        ident = oassign.ident
        #print "eth_reg_oassign(ident='%s')" % (ident)
        if ident in self.oassign:
            if self.oassign[ident] == oassign:
                return  # OK - already defined
            else:
                raise DuplicateError("information object assignment", ident)
        self.oassign[ident] = oassign
        self.oassign_ord.append(ident)
        self.oassign_cls.setdefault(oassign.cls, []).append(ident)

    #--- eth_import_type --------------------------------------------------------
    def eth_import_type(self, ident, mod, proto):
        #print "eth_import_type(ident='%s', mod='%s', prot='%s')" % (ident, mod, proto)
        if ident in self.type:
            #print "already defined '%s' import=%s, module=%s" % (ident, str(self.type[ident]['import']), self.type[ident].get('module', '-'))
            if not self.type[ident]['import'] and (self.type[ident]['module'] == mod) :
                return  # OK - already defined
            elif self.type[ident]['import'] and (self.type[ident]['import'] == mod) :
                return  # OK - already imported
            else:
                raise DuplicateError("type", ident)
        self.type[ident] = {'import'  : mod, 'proto' : proto,
                            'ethname' : '' }
        self.type[ident]['attr'] = { 'TYPE' : 'FT_NONE', 'DISPLAY' : 'BASE_NONE',
                                     'STRINGS' : 'NULL', 'BITMASK' : '0' }
        mident = "$%s$%s" % (mod, ident)
        if (self.conform.check_item('TYPE_ATTR', mident)):
            self.type[ident]['attr'].update(self.conform.use_item('TYPE_ATTR', mident))
869
        else:
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
            self.type[ident]['attr'].update(self.conform.use_item('TYPE_ATTR', ident))
        if (self.conform.check_item('IMPORT_TAG', mident)):
            self.conform.copy_item('IMPORT_TAG', ident, mident)
        self.type_imp.append(ident)

    #--- dummy_import_type --------------------------------------------------------
    def dummy_import_type(self, ident):
        # dummy imported
        if ident in self.type:
            raise Exception("Try to dummy import for existing type :%s" % ident)
        ethtype = asn2c(ident)
        self.type[ident] = {'import'  : 'xxx', 'proto' : 'xxx',
                            'ethname' : ethtype }
        self.type[ident]['attr'] = { 'TYPE' : 'FT_NONE', 'DISPLAY' : 'BASE_NONE',
                                     'STRINGS' : 'NULL', 'BITMASK' : '0' }
        self.eth_type[ethtype] = { 'import' : 'xxx', 'proto' : 'xxx' , 'attr' : {}, 'ref' : []}
        print("Dummy imported: %s (%s)" % (ident, ethtype))
        return ethtype

    #--- eth_import_class --------------------------------------------------------
    def eth_import_class(self, ident, mod, proto):
        #print "eth_import_class(ident='%s', mod='%s', prot='%s')" % (ident, mod, proto)
        if ident in self.objectclass:
            #print "already defined import=%s, module=%s" % (str(self.objectclass[ident]['import']), self.objectclass[ident]['module'])
            if not self.objectclass[ident]['import'] and (self.objectclass[ident]['module'] == mod) :
                return  # OK - already defined
            elif self.objectclass[ident]['import'] and (self.objectclass[ident]['import'] == mod) :
                return  # OK - already imported
            else:
                raise DuplicateError("object class", ident)
        self.objectclass[ident] = {'import'  : mod, 'proto' : proto,
                            'ethname' : '' }
        self.objectclass_imp.append(ident)

    #--- eth_import_value -------------------------------------------------------
    def eth_import_value(self, ident, mod, proto):
        #print "eth_import_value(ident='%s', mod='%s', prot='%s')" % (ident, mod, prot)
        if ident in self.value:
            #print "already defined import=%s, module=%s" % (str(self.value[ident]['import']), self.value[ident]['module'])
            if not self.value[ident]['import'] and (self.value[ident]['module'] == mod) :
                return  # OK - already defined
            elif self.value[ident]['import'] and (self.value[ident]['import'] == mod) :
                return  # OK - already imported
            else:
                raise DuplicateError("value", ident)
        self.value[ident] = {'import'  : mod, 'proto' : proto,
                             'ethname' : ''}
        self.value_imp.append(ident)

    #--- eth_sel_req ------------------------------------------------------------
    def eth_sel_req(self, typ, sel):
        key = typ + '.' + sel
        if key not in self.sel_req:
            self.sel_req[key] = { 'typ' : typ , 'sel' : sel}
            self.sel_req_ord.append(key)
        return key

    #--- eth_comp_req ------------------------------------------------------------
    def eth_comp_req(self, type):
        self.comp_req_ord.append(type)

    #--- eth_dep_add ------------------------------------------------------------
    def eth_dep_add(self, type, dep):
        if type not in self.type_dep:
            self.type_dep[type] = []
        self.type_dep[type].append(dep)

    #--- eth_reg_type -----------------------------------------------------------
    def eth_reg_type(self, ident, val):
        #print "eth_reg_type(ident='%s', type='%s')" % (ident, val.type)
        if ident in self.type:
            if self.type[ident]['import'] and (self.type[ident]['import'] == self.Module()) :
                # replace imported type
                del self.type[ident]
                self.type_imp.remove(ident)
            else:
                raise DuplicateError("type", ident)
        val.ident = ident
        self.type[ident] = { 'val' : val, 'import' : None }
        self.type[ident]['module'] = self.Module()
        self.type[ident]['proto'] = self.proto
        if len(ident.split('/')) > 1:
            self.type[ident]['tname'] = val.eth_tname()
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
953
        else:
954 955 956 957 958 959 960 961 962 963
            self.type[ident]['tname'] = asn2c(ident)
        self.type[ident]['export'] = self.conform.use_item('EXPORTS', ident)
        self.type[ident]['enum'] = self.conform.use_item('MAKE_ENUM', ident)
        self.type[ident]['vals_ext'] = self.conform.use_item('USE_VALS_EXT', ident)
        self.type[ident]['user_def'] = self.conform.use_item('USER_DEFINED', ident)
        self.type[ident]['no_emit'] = self.conform.use_item('NO_EMIT', ident)
        self.type[ident]['tname'] = self.conform.use_item('TYPE_RENAME', ident, val_dflt=self.type[ident]['tname'])
        self.type[ident]['ethname'] = ''
        if (val.type == 'Type_Ref') or (val.type == 'TaggedType') or (val.type == 'SelectionType') :
            self.type[ident]['attr'] = {}
964
        else:
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
            (ftype, display) = val.eth_ftype(self)
            self.type[ident]['attr'] = { 'TYPE' : ftype, 'DISPLAY' : display,
                                         'STRINGS' : val.eth_strings(), 'BITMASK' : '0' }
        self.type[ident]['attr'].update(self.conform.use_item('TYPE_ATTR', ident))
        self.type_ord.append(ident)
        # PDU
        if (self.conform.check_item('PDU', ident)):
            self.eth_reg_field(ident, ident, impl=val.HasImplicitTag(self), pdu=self.conform.use_item('PDU', ident))

    #--- eth_reg_objectclass ----------------------------------------------------------
    def eth_reg_objectclass(self, ident, val):
        #print "eth_reg_objectclass(ident='%s')" % (ident)
        if ident in self.objectclass:
            if self.objectclass[ident]['import'] and (self.objectclass[ident]['import'] == self.Module()) :
                # replace imported object class
                del self.objectclass[ident]
                self.objectclass_imp.remove(ident)
            elif isinstance(self.objectclass[ident]['val'], Class_Ref) and \
                 isinstance(val, Class_Ref) and \
                 (self.objectclass[ident]['val'].val == val.val):
                pass  # ignore duplicated CLASS1 ::= CLASS2
            else:
                raise DuplicateError("object class", ident)
        self.objectclass[ident] = { 'import' : None, 'module' : self.Module(), 'proto' : self.proto }
        self.objectclass[ident]['val'] = val
        self.objectclass[ident]['export'] = self.conform.use_item('EXPORTS', ident)
        self.objectclass_ord.append(ident)

    #--- eth_reg_value ----------------------------------------------------------
    def eth_reg_value(self, ident, type, value, ethname=None):
        #print "eth_reg_value(ident='%s')" % (ident)
        if ident in self.value:
            if self.value[ident]['import'] and (self.value[ident]['import'] == self.Module()) :
                # replace imported value
                del self.value[ident]
                self.value_imp.remove(ident)
            elif ethname:
                self.value[ident]['ethname'] = ethname
                return
            else:
                raise DuplicateError("value", ident)
        self.value[ident] = { 'import' : None, 'module' : self.Module(), 'proto' : self.proto,
                              'type' : type, 'value' : value,
                              'no_emit' : False }
        self.value[ident]['export'] = self.conform.use_item('EXPORTS', ident)
        self.value[ident]['ethname'] = ''
        if (ethname): self.value[ident]['ethname'] = ethname
        self.value_ord.append(ident)

    #--- eth_reg_field ----------------------------------------------------------
    def eth_reg_field(self, ident, type, idx='', parent=None, impl=False, pdu=None):
        #print "eth_reg_field(ident='%s', type='%s')" % (ident, type)
        if ident in self.field:
            if pdu and (type == self.field[ident]['type']):
                pass  # OK already created PDU
            else:
                raise DuplicateError("field", ident)
        self.field[ident] = {'type' : type, 'idx' : idx, 'impl' : impl, 'pdu' : pdu,
                             'modified' : '', 'attr' : {} }
        name = ident.split('/')[-1]
        if self.remove_prefix and name.startswith(self.remove_prefix):
            name = name[len(self.remove_prefix):]

        if len(ident.split('/')) > 1 and name == ITEM_FIELD_NAME:  # Sequence/Set of type
            if len(self.field[ident]['type'].split('/')) > 1:
                self.field[ident]['attr']['NAME'] = '"%s item"' % ident.split('/')[-2]
                self.field[ident]['attr']['ABBREV'] = asn2c(ident.split('/')[-2] + name)
            else:
                self.field[ident]['attr']['NAME'] = '"%s"' % self.field[ident]['type']
                self.field[ident]['attr']['ABBREV'] = asn2c(self.field[ident]['type'])
        else:
            self.field[ident]['attr']['NAME'] = '"%s"' % name
            self.field[ident]['attr']['ABBREV'] = asn2c(name)
        if self.conform.check_item('FIELD_ATTR', ident):
            self.field[ident]['modified'] = '#' + str(id(self))
            self.field[ident]['attr'].update(self.conform.use_item('FIELD_ATTR', ident))
        if (pdu):
            self.field[ident]['pdu']['export'] = (self.conform.use_item('EXPORTS', ident + '_PDU') != 0)
            self.pdu_ord.append(ident)
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
1044
        else:
1045 1046 1047 1048 1049 1050
            self.field_ord.append(ident)
        if parent:
            self.eth_dep_add(parent, type)

    def eth_dummy_eag_field_required(self):
        if (not self.dummy_eag_field):
1051
            self.dummy_eag_field = 'eag_field'
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343

    #--- eth_clean --------------------------------------------------------------
    def eth_clean(self):
        self.proto = self.proto_opt;
        #--- ASN.1 tables ----------------
        self.assign = {}
        self.assign_ord = []
        self.field = {}
        self.pdu_ord = []
        self.field_ord = []
        self.type = {}
        self.type_ord = []
        self.type_imp = []
        self.type_dep = {}
        self.sel_req = {}
        self.sel_req_ord = []
        self.comp_req_ord = []
        self.vassign = {}
        self.vassign_ord = []
        self.value = {}
        self.value_ord = []
        self.value_imp = []
        self.objectclass = {}
        self.objectclass_ord = []
        self.objectclass_imp = []
        self.oassign = {}
        self.oassign_ord = []
        self.oassign_cls = {}
        #--- Modules ------------
        self.modules = []
        self.exports_all = False
        self.exports = []
        self.cexports = []
        self.vexports = []
        #--- types -------------------
        self.eth_type = {}
        self.eth_type_ord = []
        self.eth_export_ord = []
        self.eth_type_dupl = {}
        self.named_bit = []
        #--- value dependencies -------------------
        self.value_dep = {}
        #--- values -------------------
        self.eth_value = {}
        self.eth_value_ord = []
        #--- fields -------------------------
        self.eth_hf = {}
        self.eth_hf_ord = []
        self.eth_hfpdu_ord = []
        self.eth_hf_dupl = {}
        self.dummy_eag_field = None
        #--- type dependencies -------------------
        self.eth_type_ord1 = []
        self.eth_dep_cycle = []
        self.dep_cycle_eth_type = {}
        #--- value dependencies and export -------------------
        self.eth_value_ord1 = []
        self.eth_vexport_ord = []

    #--- eth_prepare ------------------------------------------------------------
    def eth_prepare(self):
        self.eproto = asn2c(self.proto)

        #--- dummy types/fields for PDU registration ---
        nm = 'NULL'
        if (self.conform.check_item('PDU', nm)):
            self.eth_reg_type('_dummy/'+nm, NullType())
            self.eth_reg_field(nm, '_dummy/'+nm, pdu=self.conform.use_item('PDU', nm))

        #--- required PDUs ----------------------------
        for t in self.type_ord:
            pdu = self.type[t]['val'].eth_need_pdu(self)
            if not pdu: continue
            f = pdu['type']
            pdu['reg'] = None
            pdu['hidden'] = False
            pdu['need_decl'] = True
            if f not in self.field:
                self.eth_reg_field(f, f, pdu=pdu)

        #--- values -> named values -------------------
        t_for_update = {}
        for v in self.value_ord:
            if (self.value[v]['type'].type == 'Type_Ref') or self.conform.check_item('ASSIGN_VALUE_TO_TYPE', v):
                if self.conform.check_item('ASSIGN_VALUE_TO_TYPE', v):
                    tnm = self.conform.use_item('ASSIGN_VALUE_TO_TYPE', v)
                else:
                    tnm = self.value[v]['type'].val
                if tnm in self.type \
                   and not self.type[tnm]['import'] \
                   and (self.type[tnm]['val'].type == 'IntegerType'):
                    self.type[tnm]['val'].add_named_value(v, self.value[v]['value'])
                    self.value[v]['no_emit'] = True
                    t_for_update[tnm] = True
        for t in list(t_for_update.keys()):
            self.type[t]['attr']['STRINGS'] = self.type[t]['val'].eth_strings()
            self.type[t]['attr'].update(self.conform.use_item('TYPE_ATTR', t))

        #--- required components of ---------------------------
        #print "self.comp_req_ord = ", self.comp_req_ord
        for t in self.comp_req_ord:
            self.type[t]['val'].eth_reg_sub(t, self, components_available=True)

        #--- required selection types ---------------------------
        #print "self.sel_req_ord = ", self.sel_req_ord
        for t in self.sel_req_ord:
            tt = self.sel_req[t]['typ']
            if tt not in self.type:
                self.dummy_import_type(t)
            elif self.type[tt]['import']:
                self.eth_import_type(t, self.type[tt]['import'], self.type[tt]['proto'])
            else:
                self.type[tt]['val'].sel_req(t, self.sel_req[t]['sel'], self)

        #--- types -------------------
        for t in self.type_imp: # imported types
            nm = asn2c(t)
            self.eth_type[nm] = { 'import' : self.type[t]['import'],
                                  'proto' : asn2c(self.type[t]['proto']),
                                  'attr' : {}, 'ref' : []}
            self.eth_type[nm]['attr'].update(self.conform.use_item('ETYPE_ATTR', nm))
            self.type[t]['ethname'] = nm
        for t in self.type_ord: # dummy import for missing type reference
            tp = self.type[t]['val']
            #print "X : %s %s " % (t, tp.type)
            if isinstance(tp, TaggedType):
                #print "%s : %s " % (tp.type, t)
                tp = tp.val
            if isinstance(tp, Type_Ref):
                #print "%s : %s ::= %s " % (tp.type, t, tp.val)
                if tp.val not in self.type:
                    self.dummy_import_type(tp.val)
        for t in self.type_ord:
            nm = self.type[t]['tname']
            if ((nm.find('#') >= 0) or
                ((len(t.split('/'))>1) and
                 (self.conform.get_fn_presence(t) or self.conform.check_item('FN_PARS', t) or
                  self.conform.get_fn_presence('/'.join((t,ITEM_FIELD_NAME))) or self.conform.check_item('FN_PARS', '/'.join((t,ITEM_FIELD_NAME)))) and
                 not self.conform.check_item('TYPE_RENAME', t))):
                if len(t.split('/')) == 2 and t.split('/')[1] == ITEM_FIELD_NAME:  # Sequence of type at the 1st level
                    nm = t.split('/')[0] + t.split('/')[1]
                elif t.split('/')[-1] == ITEM_FIELD_NAME:  # Sequence/Set of type at next levels
                    nm = 'T_' + self.conform.use_item('FIELD_RENAME', '/'.join(t.split('/')[0:-1]), val_dflt=t.split('/')[-2]) + t.split('/')[-1]
                elif t.split('/')[-1] == UNTAG_TYPE_NAME:  # Untagged type
                    nm = self.type['/'.join(t.split('/')[0:-1])]['ethname'] + '_U'
                else:
                    nm = 'T_' + self.conform.use_item('FIELD_RENAME', t, val_dflt=t.split('/')[-1])
                nm = asn2c(nm)
                if nm in self.eth_type:
                    if nm in self.eth_type_dupl:
                        self.eth_type_dupl[nm].append(t)
                    else:
                        self.eth_type_dupl[nm] = [self.eth_type[nm]['ref'][0], t]
                    nm += '_%02d' % (len(self.eth_type_dupl[nm])-1)
            if nm in self.eth_type:
                self.eth_type[nm]['ref'].append(t)
            else:
                self.eth_type_ord.append(nm)
                self.eth_type[nm] = { 'import' : None, 'proto' : self.eproto, 'export' : 0, 'enum' : 0, 'vals_ext' : 0,
                                      'user_def' : EF_TYPE|EF_VALS, 'no_emit' : EF_TYPE|EF_VALS,
                                      'val' : self.type[t]['val'],
                                      'attr' : {}, 'ref' : [t]}
            self.type[t]['ethname'] = nm
            if (not self.eth_type[nm]['export'] and self.type[t]['export']):  # new export
                self.eth_export_ord.append(nm)
            self.eth_type[nm]['export'] |= self.type[t]['export']
            self.eth_type[nm]['enum'] |= self.type[t]['enum']
            self.eth_type[nm]['vals_ext'] |= self.type[t]['vals_ext']
            self.eth_type[nm]['user_def'] &= self.type[t]['user_def']
            self.eth_type[nm]['no_emit'] &= self.type[t]['no_emit']
            if self.type[t]['attr'].get('STRINGS') == '$$':
                use_ext = self.type[t]['vals_ext']
                if (use_ext):
                    self.eth_type[nm]['attr']['STRINGS'] = '&%s_ext' % (self.eth_vals_nm(nm))
                else:
                    self.eth_type[nm]['attr']['STRINGS'] = 'VALS(%s)' % (self.eth_vals_nm(nm))
            self.eth_type[nm]['attr'].update(self.conform.use_item('ETYPE_ATTR', nm))
        for t in self.eth_type_ord:
            bits = self.eth_type[t]['val'].eth_named_bits()
            if (bits):
                for (val, id) in bits:
                    self.named_bit.append({'name' : id, 'val' : val,
                                           'ethname' : 'hf_%s_%s_%s' % (self.eproto, t, asn2c(id)),
                                           'ftype'   : 'FT_BOOLEAN', 'display' : '8',
                                           'strings' : 'NULL',
                                           'bitmask' : '0x'+('80','40','20','10','08','04','02','01')[val%8]})
            if self.eth_type[t]['val'].eth_need_tree():
                self.eth_type[t]['tree'] = "ett_%s_%s" % (self.eth_type[t]['proto'], t)
            else:
                self.eth_type[t]['tree'] = None

        #--- register values from enums ------------
        for t in self.eth_type_ord:
            if (self.eth_type[t]['val'].eth_has_enum(t, self)):
                self.eth_type[t]['val'].reg_enum_vals(t, self)

        #--- value dependencies -------------------
        for v in self.value_ord:
            if isinstance (self.value[v]['value'], Value):
                dep = self.value[v]['value'].get_dep()
            else:
                dep = self.value[v]['value']
            if dep and dep in self.value:
                self.value_dep.setdefault(v, []).append(dep)

        #--- exports all necessary values
        for v in self.value_ord:
            if not self.value[v]['export']: continue
            deparr = self.value_dep.get(v, [])
            while deparr:
                d = deparr.pop()
                if not self.value[d]['import']:
                    if not self.value[d]['export']:
                        self.value[d]['export'] = EF_TYPE
                        deparr.extend(self.value_dep.get(d, []))

        #--- values -------------------
        for v in self.value_imp:
            nm = asn2c(v)
            self.eth_value[nm] = { 'import' : self.value[v]['import'],
                                   'proto' : asn2c(self.value[v]['proto']),
                                   'ref' : []}
            self.value[v]['ethname'] = nm
        for v in self.value_ord:
            if (self.value[v]['ethname']):
                continue
            if (self.value[v]['no_emit']):
                continue
            nm = asn2c(v)
            self.eth_value[nm] = { 'import' : None,
                                   'proto' : asn2c(self.value[v]['proto']),
                                   'export' : self.value[v]['export'], 'ref' : [v] }
            self.eth_value[nm]['value'] = self.value[v]['value']
            self.eth_value_ord.append(nm)
            self.value[v]['ethname'] = nm

        #--- fields -------------------------
        for f in (self.pdu_ord + self.field_ord):
            if len(f.split('/')) > 1 and f.split('/')[-1] == ITEM_FIELD_NAME:  # Sequence/Set of type
                nm = self.conform.use_item('FIELD_RENAME', '/'.join(f.split('/')[0:-1]), val_dflt=f.split('/')[-2]) + f.split('/')[-1]
            else:
                nm = f.split('/')[-1]
            nm = self.conform.use_item('FIELD_RENAME', f, val_dflt=nm)
            nm = asn2c(nm)
            if (self.field[f]['pdu']):
                nm += '_PDU'
                if (not self.merge_modules or self.field[f]['pdu']['export']):
                    nm = self.eproto + '_' + nm
            t = self.field[f]['type']
            if t in self.type:
                ethtype = self.type[t]['ethname']
            else:  # undefined type
                ethtype = self.dummy_import_type(t)
            ethtypemod = ethtype + self.field[f]['modified']
            if nm in self.eth_hf:
                if nm in self.eth_hf_dupl:
                    if ethtypemod in self.eth_hf_dupl[nm]:
                        nm = self.eth_hf_dupl[nm][ethtypemod]
                        self.eth_hf[nm]['ref'].append(f)
                        self.field[f]['ethname'] = nm
                        continue
                    else:
                        nmx = nm + ('_%02d' % (len(self.eth_hf_dupl[nm])))
                        self.eth_hf_dupl[nm][ethtype] = nmx
                        nm = nmx
                else:
                    if (self.eth_hf[nm]['ethtype']+self.eth_hf[nm]['modified']) == ethtypemod:
                        self.eth_hf[nm]['ref'].append(f)
                        self.field[f]['ethname'] = nm
                        continue
                    else:
                        nmx = nm + '_01'
                        self.eth_hf_dupl[nm] = {self.eth_hf[nm]['ethtype']+self.eth_hf[nm]['modified'] : nm, \
                                                ethtypemod : nmx}
                        nm = nmx
            if (self.field[f]['pdu']):
                self.eth_hfpdu_ord.append(nm)
            else:
                self.eth_hf_ord.append(nm)
            fullname = 'hf_%s_%s' % (self.eproto, nm)
            attr = self.eth_get_type_attr(self.field[f]['type']).copy()
            attr.update(self.field[f]['attr'])
            if (self.NAPI() and 'NAME' in attr):
                attr['NAME'] += self.field[f]['idx']
            attr.update(self.conform.use_item('EFIELD_ATTR', nm))
            use_vals_ext = self.eth_type[ethtype].get('vals_ext')
            if (use_vals_ext):
                attr['DISPLAY'] += '|BASE_EXT_STRING'
            self.eth_hf[nm] = {'fullname' : fullname, 'pdu' : self.field[f]['pdu'],
                               'ethtype' : ethtype, 'modified' : self.field[f]['modified'],
                               'attr' : attr.copy(),
                               'ref' : [f]}
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
1344
            self.field[f]['ethname'] = nm
1345
        if (self.dummy_eag_field):
1346 1347
            # Prepending "dummy_" avoids matching checkhf.pl.
            self.dummy_eag_field = 'dummy_hf_%s_%s' % (self.eproto, self.dummy_eag_field)
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
        #--- type dependencies -------------------
        (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'])
        i = 0
        while i < len(self.eth_dep_cycle):
            t = self.type[self.eth_dep_cycle[i][0]]['ethname']
            self.dep_cycle_eth_type.setdefault(t, []).append(i)
            i += 1

        #--- value dependencies and export -------------------
        for v in self.eth_value_ord:
            if self.eth_value[v]['export']:
                self.eth_vexport_ord.append(v)
            else:
                self.eth_value_ord1.append(v)

        #--- export tags, values, ... ---
        for t in self.exports:
            if t not in self.type:
                continue
            if self.type[t]['import']:
                continue
            m = self.type[t]['module']
            if not self.Per():
                if m not in self.all_tags:
                    self.all_tags[m] = {}
                self.all_tags[m][t] = self.type[t]['val'].GetTTag(self)
            if m not in self.all_type_attr:
                self.all_type_attr[m] = {}
            self.all_type_attr[m][t] = self.eth_get_type_attr(t).copy()
        for v in self.vexports:
            if v not in self.value:
                continue
            if self.value[v]['import']:
                continue
            m = self.value[v]['module']
            if m not in self.all_vals:
                self.all_vals[m] = {}
            vv = self.value[v]['value']
            if isinstance (vv, Value):
                vv = vv.to_str(self)
            self.all_vals[m][v] = vv

    #--- eth_vals_nm ------------------------------------------------------------
    def eth_vals_nm(self, tname):
        out = ""
        if (not self.eth_type[tname]['export'] & EF_NO_PROT):
            out += "%s_" % (self.eproto)
        out += "%s_vals" % (tname)
        return out

    #--- eth_vals ---------------------------------------------------------------
    def eth_vals(self, tname, vals):
        out = ""
        has_enum = self.eth_type[tname]['enum'] & EF_ENUM
        use_ext = self.eth_type[tname]['vals_ext']
        if (use_ext):
            vals.sort(key=lambda vals_entry: int(vals_entry[0]))
        if (not self.eth_type[tname]['export'] & EF_VALS):
            out += 'static '
        if (self.eth_type[tname]['export'] & EF_VALS) and (self.eth_type[tname]['export'] & EF_TABLE):
            out += 'static '
        out += "const value_string %s[] = {\n" % (self.eth_vals_nm(tname))
        for (val, id) in vals:
            if (has_enum):
                vval = self.eth_enum_item(tname, id)
            else:
                vval = val
            out += '  { %3s, "%s" },\n' % (vval, id)
        out += "  { 0, NULL }\n};\n"
        if (use_ext):
            out += "\nstatic value_string_ext %s_ext = VALUE_STRING_EXT_INIT(%s);\n" % (self.eth_vals_nm(tname), self.eth_vals_nm(tname))
        return out

    #--- eth_enum_prefix ------------------------------------------------------------
    def eth_enum_prefix(self, tname, type=False):
        out = ""
        if (self.eth_type[tname]['export'] & EF_ENUM):
            no_prot = self.eth_type[tname]['export'] & EF_NO_PROT
1426
        else:
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
            no_prot = self.eth_type[tname]['enum'] & EF_NO_PROT
        if (not no_prot):
            out += self.eproto
        if ((not self.eth_type[tname]['enum'] & EF_NO_TYPE) or type):
            if (out): out += '_'
            out += tname
        if (self.eth_type[tname]['enum'] & EF_UCASE):
            out = out.upper()
        if (out): out += '_'
        return out

    #--- eth_enum_nm ------------------------------------------------------------
    def eth_enum_nm(self, tname):
        out = self.eth_enum_prefix(tname, type=True)
        out += "enum"
        return out

    #--- eth_enum_item ---------------------------------------------------------------
    def eth_enum_item(self, tname, ident):
        out = self.eth_enum_prefix(tname)
        out += asn2c(ident)
        if (self.eth_type[tname]['enum'] & EF_UCASE):
            out = out.upper()
        return out

    #--- eth_enum ---------------------------------------------------------------
    def eth_enum(self, tname, vals):
        out = ""
        if (self.eth_type[tname]['enum'] & EF_DEFINE):
            out += "/* enumerated values for %s */\n" % (tname)
            for (val, id) in vals:
                out += '#define %-12s %3s\n' % (self.eth_enum_item(tname, id), val)
1459
        else:
1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
            out += "typedef enum _%s {\n" % (self.eth_enum_nm(tname))
            first_line = 1
            for (val, id) in vals:
                if (first_line == 1):
                    first_line = 0
                else:
                    out += ",\n"
                out += '  %-12s = %3s' % (self.eth_enum_item(tname, id), val)
            out += "\n} %s;\n" % (self.eth_enum_nm(tname))
        return out

    #--- eth_bits ---------------------------------------------------------------
    def eth_bits(self, tname, bits):
        out = ""
        out += "static const "
        out += "asn_namedbit %(TABLE)s[] = {\n"
        for (val, id) in bits:
            out += '  { %2d, &hf_%s_%s_%s, -1, -1, "%s", NULL },\n' % (val, self.eproto, tname, asn2c(id), id)
        out += "  { 0, NULL, 0, 0, NULL, NULL }\n};\n"
        return out

    #--- eth_type_fn_h ----------------------------------------------------------
    def eth_type_fn_h(self, tname):
        out = ""
        if (not self.eth_type[tname]['export'] & EF_TYPE):
            out += 'static '
        out += "int "
        if (self.Ber()):
            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)
        elif (self.Per()):
            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)
        out += ";\n"
        return out

    #--- eth_fn_call ------------------------------------------------------------
    def eth_fn_call(self, fname, ret=None, indent=2, par=None):
        out = indent * ' '
        if (ret):
            if (ret == 'return'):
                out += 'return '
            else:
                out += ret + ' = '
        out += fname + '('
        ind = len(out)
        for i in range(len(par)):
            if (i>0): out += ind * ' '
            out += ', '.join(par[i])
            if (i<(len(par)-1)): out += ',\n'
        out += ');\n'
        return out

    #--- eth_type_fn_hdr --------------------------------------------------------
    def eth_type_fn_hdr(self, tname):
        out = '\n'
        if (not self.eth_type[tname]['export'] & EF_TYPE):
            out += 'static '
        out += "int\n"
        if (self.Ber()):
            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)
        elif (self.Per()):
            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)
        #if self.conform.get_fn_presence(tname):
        #  out += self.conform.get_fn_text(tname, 'FN_HDR')
        #el
        if self.conform.get_fn_presence(self.eth_type[tname]['ref'][0]):
            out += self.conform.get_fn_text(self.eth_type[tname]['ref'][0], 'FN_HDR')
        return out

    #--- eth_type_fn_ftr --------------------------------------------------------
    def eth_type_fn_ftr(self, tname):
        out = '\n'
        #if self.conform.get_fn_presence(tname):
        #  out += self.conform.get_fn_text(tname, 'FN_FTR')
        #el
        if self.conform.get_fn_presence(self.eth_type[tname]['ref'][0]):
            out += self.conform.get_fn_text(self.eth_type[tname]['ref'][0], 'FN_FTR')
        out += "  return offset;\n"
        out += "}\n"
        return out

    #--- eth_type_fn_body -------------------------------------------------------
    def eth_type_fn_body(self, tname, body, pars=None):
        out = body
        #if self.conform.get_fn_body_presence(tname):
        #  out = self.conform.get_fn_text(tname, 'FN_BODY')
        #el
        if self.conform.get_fn_body_presence(self.eth_type[tname]['ref'][0]):
            out = self.conform.get_fn_text(self.eth_type[tname]['ref'][0], 'FN_BODY')
        if pars:
            try:
                out = out % pars
            except (TypeError):
                pass
        return out

    #--- eth_out_pdu_decl ----------------------------------------------------------
    def eth_out_pdu_decl(self, f):
        t = self.eth_hf[f]['ethtype']
        out = ''
        if (not self.eth_hf[f]['pdu']['export']):
            out += 'static '
1561 1562
        out += 'int '
        out += 'dissect_'+f+'(tvbuff_t *tvb _U_, packet_info *pinfo _U_, proto_tree *tree _U_, void *data _U_);\n'
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
        return out

    #--- eth_output_hf ----------------------------------------------------------
    def eth_output_hf (self):
        if not len(self.eth_hf_ord) and not len(self.eth_hfpdu_ord) and not len(self.named_bit): return
        fx = self.output.file_open('hf')
        for f in (self.eth_hfpdu_ord + self.eth_hf_ord):
            fx.write("%-50s/* %s */\n" % ("static int %s = -1;  " % (self.eth_hf[f]['fullname']), self.eth_hf[f]['ethtype']))
        if (self.named_bit):
            fx.write('/* named bits */\n')
        for nb in self.named_bit:
            fx.write("static int %s = -1;\n" % (nb['ethname']))
        if (self.dummy_eag_field):
1576
            fx.write("static int %s = -1; /* never registered */\n" % (self.dummy_eag_field))
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
        self.output.file_close(fx)

    #--- eth_output_hf_arr ------------------------------------------------------
    def eth_output_hf_arr (self):
        if not len(self.eth_hf_ord) and not len(self.eth_hfpdu_ord) and not len(self.named_bit): return
        fx = self.output.file_open('hfarr')
        for f in (self.eth_hfpdu_ord + self.eth_hf_ord):
            t = self.eth_hf[f]['ethtype']
            if self.remove_prefix and t.startswith(self.remove_prefix):
                t = t[len(self.remove_prefix):]
            name=self.eth_hf[f]['attr']['NAME']
            try: # Python < 3
                trantab = maketrans("- ", "__")
            except:
                trantab = str.maketrans("- ", "__")
            name = name.translate(trantab)
            namelower = name.lower()
            tquoted_lower = '"' + t.lower() + '"'
            # Try to avoid giving blurbs that give no more info than the name
            if tquoted_lower == namelower or \
               t == "NULL" or \
               tquoted_lower.replace("t_", "") == namelower:
                blurb = 'NULL'
            else:
                blurb = '"%s"' % (t)
            attr = self.eth_hf[f]['attr'].copy()
            if attr['TYPE'] == 'FT_NONE':
                attr['ABBREV'] = '"%s.%s_element"' % (self.proto, attr['ABBREV'])
            else:
                attr['ABBREV'] = '"%s.%s"' % (self.proto, attr['ABBREV'])
            if 'BLURB' not in attr:
                attr['BLURB'] = blurb
            fx.write('    { &%s,\n' % (self.eth_hf[f]['fullname']))
            fx.write('      { %(NAME)s, %(ABBREV)s,\n' % attr)
            fx.write('        %(TYPE)s, %(DISPLAY)s, %(STRINGS)s, %(BITMASK)s,\n' % attr)
            fx.write('        %(BLURB)s, HFILL }},\n' % attr)
        for nb in self.named_bit:
            fx.write('    { &%s,\n' % (nb['ethname']))
            fx.write('      { "%s", "%s.%s",\n' % (nb['name'], self.proto, nb['name']))
            fx.write('        %s, %s, %s, %s,\n' % (nb['ftype'], nb['display'], nb['strings'], nb['bitmask']))
            fx.write('        NULL, HFILL }},\n')
        self.output.file_close(fx)

    #--- eth_output_ett ---------------------------------------------------------
    def eth_output_ett (self):
        fx = self.output.file_open('ett')
        fempty = True
        #fx.write("static gint ett_%s = -1;\n" % (self.eproto))
        for t in self.eth_type_ord:
            if self.eth_type[t]['tree']:
                fx.write("static gint %s = -1;\n" % (self.eth_type[t]['tree']))
                fempty = False
        self.output.file_close(fx, discard=fempty)

    #--- eth_output_ett_arr -----------------------------------------------------
    def eth_output_ett_arr(self):
        fx = self.output.file_open('ettarr')
        fempty = True
        #fx.write("    &ett_%s,\n" % (self.eproto))
        for t in self.eth_type_ord:
            if self.eth_type[t]['tree']:
                fx.write("    &%s,\n" % (self.eth_type[t]['tree']))
                fempty = False
        self.output.file_close(fx, discard=fempty)

    #--- eth_output_export ------------------------------------------------------
    def eth_output_export(self):
        fx = self.output.file_open('exp', ext='h')
        for t in self.eth_export_ord:  # vals
            if (self.eth_type[t]['export'] & EF_ENUM) and self.eth_type[t]['val'].eth_has_enum(t, self):
                fx.write(self.eth_type[t]['val'].eth_type_enum(t, self))
            if (self.eth_type[t]['export'] & EF_VALS) and self.eth_type[t]['val'].eth_has_vals():
                if not self.eth_type[t]['export'] & EF_TABLE:
                    if self.eth_type[t]['export'] & EF_WS_DLL:
                        fx.write("WS_DLL_PUBLIC ")
                    else:
                        fx.write("extern ")
                    fx.write("const value_string %s[];\n" % (self.eth_vals_nm(t)))
                else:
                    fx.write(self.eth_type[t]['val'].eth_type_vals(t, self))
        for t in self.eth_export_ord:  # functions
            if (self.eth_type[t]['export'] & EF_TYPE):
                if self.eth_type[t]['export'] & EF_EXTERN:
                    if self.eth_type[t]['export'] & EF_WS_DLL:
                        fx.write("WS_DLL_PUBLIC ")
                    else:
                        fx.write("extern ")
                fx.write(self.eth_type_fn_h(t))
        for f in self.eth_hfpdu_ord:  # PDUs
            if (self.eth_hf[f]['pdu'] and self.eth_hf[f]['pdu']['export']):
                fx.write(self.eth_out_pdu_decl(f))
        self.output.file_close(fx)

    #--- eth_output_expcnf ------------------------------------------------------
    def eth_output_expcnf(self):
        fx = self.output.file_open('exp', ext='cnf')
        fx.write('#.MODULE\n')
        maxw = 0
        for (m, p) in self.modules:
            if (len(m) > maxw): maxw = len(m)
        for (m, p) in self.modules:
            fx.write("%-*s  %s\n" % (maxw, m, p))
        fx.write('#.END\n\n')
        for cls in self.objectclass_ord:
            if self.objectclass[cls]['export']:
                cnm = cls
                if self.objectclass[cls]['export'] & EF_MODULE:
                    cnm = "$%s$%s" % (self.objectclass[cls]['module'], cnm)
                fx.write('#.CLASS %s\n' % (cnm))
                maxw = 2
                for fld in self.objectclass[cls]['val'].fields:
                    w = len(fld.fld_repr()[0])
                    if (w > maxw): maxw = w
                for fld in self.objectclass[cls]['val'].fields:
                    repr = fld.fld_repr()
                    fx.write('%-*s  %s\n' % (maxw, repr[0], ' '.join(repr[1:])))
                fx.write('#.END\n\n')
        if self.Ber():
            fx.write('#.IMPORT_TAG\n')
            for t in self.eth_export_ord:  # tags
                if (self.eth_type[t]['export'] & EF_TYPE):
                    fx.write('%-24s ' % self.eth_type[t]['ref'][0])
                    fx.write('%s %s\n' % self.eth_type[t]['val'].GetTag(self))
            fx.write('#.END\n\n')
        fx.write('#.TYPE_ATTR\n')
        for t in self.eth_export_ord:  # attributes
            if (self.eth_type[t]['export'] & EF_TYPE):
                tnm = self.eth_type[t]['ref'][0]
                if self.eth_type[t]['export'] & EF_MODULE:
                    tnm = "$%s$%s" % (self.type[tnm]['module'], tnm)
                fx.write('%-24s ' % tnm)
                attr = self.eth_get_type_attr(self.eth_type[t]['ref'][0]).copy()
                fx.write('TYPE = %(TYPE)-9s  DISPLAY = %(DISPLAY)-9s  STRINGS = %(STRINGS)s  BITMASK = %(BITMASK)s\n' % attr)
        fx.write('#.END\n\n')
        self.output.file_close(fx, keep_anyway=True)

    #--- eth_output_val ------------------------------------------------------
    def eth_output_val(self):
        fx = self.output.file_open('val', ext='h')
        for v in self.eth_value_ord1:
            vv = self.eth_value[v]['value']
            if isinstance (vv, Value):
                vv = vv.to_str(self)
            fx.write("#define %-30s %s\n" % (v, vv))
        for t in self.eth_type_ord1:
            if self.eth_type[t]['import']:
                continue
            if self.eth_type[t]['val'].eth_has_enum(t, self) and not (self.eth_type[t]['export'] & EF_ENUM):
                fx.write(self.eth_type[t]['val'].eth_type_enum(t, self))
        self.output.file_close(fx)

    #--- eth_output_valexp ------------------------------------------------------
    def eth_output_valexp(self):
        if (not len(self.eth_vexport_ord)): return
        fx = self.output.file_open('valexp', ext='h')
        for v in self.eth_vexport_ord:
            vv = self.eth_value[v]['value']
            if isinstance (vv, Value):
                vv = vv.to_str(self)
            fx.write("#define %-30s %s\n" % (v, vv))
        self.output.file_close(fx)

    #--- eth_output_types -------------------------------------------------------
    def eth_output_types(self):
        def out_pdu(f):
            t = self.eth_hf[f]['ethtype']
            impl = 'FALSE'
            out = ''
            if (not self.eth_hf[f]['pdu']['export']):
                out += 'static '
1747 1748 1749 1750 1751
            out += 'int '
            out += 'dissect_'+f+'(tvbuff_t *tvb _U_, packet_info *pinfo _U_, proto_tree *tree _U_, void *data _U_) {\n'
            out += '  int offset = 0;\n'
            off_par = 'offset'
            ret_par = 'offset'
1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
            if (self.Per()):
                if (self.Aligned()):
                    aligned = 'TRUE'
                else:
                    aligned = 'FALSE'
                out += "  asn1_ctx_t asn1_ctx;\n"
                out += self.eth_fn_call('asn1_ctx_init', par=(('&asn1_ctx', 'ASN1_ENC_PER', aligned, 'pinfo'),))
            if (self.Ber()):
                out += "  asn1_ctx_t asn1_ctx;\n"
                out += self.eth_fn_call('asn1_ctx_init', par=(('&asn1_ctx', 'ASN1_ENC_BER', 'TRUE', 'pinfo'),))
                par=((impl, 'tvb', off_par,'&asn1_ctx', 'tree', self.eth_hf[f]['fullname']),)
            elif (self.Per()):
                par=(('tvb', off_par, '&asn1_ctx', 'tree', self.eth_hf[f]['fullname']),)
            else:
                par=((),)
            out += self.eth_fn_call('dissect_%s_%s' % (self.eth_type[t]['proto'], t), ret=ret_par, par=par)
1768
            if (self.Per()):
1769
                out += '  offset += 7; offset >>= 3;\n'
1770
            out += '  return offset;\n'
1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792
            out += '}\n'
            return out
        #end out_pdu()
        fx = self.output.file_open('fn')
        pos = fx.tell()
        if (len(self.eth_hfpdu_ord)):
            first_decl = True
            for f in self.eth_hfpdu_ord:
                if (self.eth_hf[f]['pdu'] and self.eth_hf[f]['pdu']['need_decl']):
                    if first_decl:
                        fx.write('/*--- PDUs declarations ---*/\n')
                        first_decl = False
                    fx.write(self.eth_out_pdu_decl(f))
            if not first_decl:
                fx.write('\n')
        if self.eth_dep_cycle:
            fx.write('/*--- Cyclic dependencies ---*/\n\n')
            i = 0
            while i < len(self.eth_dep_cycle):
                t = self.type[self.eth_dep_cycle[i][0]]['ethname']
                if self.dep_cycle_eth_type[t][0] != i: i += 1; continue
                fx.write(''.join(['/* %s */\n' % ' -> '.join(self.eth_dep_cycle[i]) for i in self.dep_cycle_eth_type[t]]))
1793 1794 1795 1796
                if not self.eth_type[t]['export'] & EF_TYPE:
                    fx.write(self.eth_type_fn_h(t))
                else:
                    fx.write('/*' + self.eth_type_fn_h(t).strip() + '*/\n')
1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843
                fx.write('\n')
                i += 1
            fx.write('\n')
        for t in self.eth_type_ord1:
            if self.eth_type[t]['import']:
                continue
            if self.eth_type[t]['val'].eth_has_vals():
                if self.eth_type[t]['no_emit'] & EF_VALS:
                    pass
                elif self.eth_type[t]['user_def'] & EF_VALS:
                    fx.write("extern const value_string %s[];\n" % (self.eth_vals_nm(t)))
                elif (self.eth_type[t]['export'] & EF_VALS) and (self.eth_type[t]['export'] & EF_TABLE):
                    pass
                else:
                    fx.write(self.eth_type[t]['val'].eth_type_vals(t, self))
            if self.eth_type[t]['no_emit'] & EF_TYPE:
                pass
            elif self.eth_type[t]['user_def'] & EF_TYPE:
                fx.write(self.eth_type_fn_h(t))
            else:
                fx.write(self.eth_type[t]['val'].eth_type_fn(self.eth_type[t]['proto'], t, self))
            fx.write('\n')
        if (len(self.eth_hfpdu_ord)):
            fx.write('/*--- PDUs ---*/\n\n')
            for f in self.eth_hfpdu_ord:
                if (self.eth_hf[f]['pdu']):
                    if (f in self.emitted_pdu):
                        fx.write("  /* %s already emitted */\n" % (f))
                    else:
                        fx.write(out_pdu(f))
                        self.emitted_pdu[f] = True
            fx.write('\n')
        fempty = pos == fx.tell()
        self.output.file_close(fx, discard=fempty)

    #--- eth_output_dis_hnd -----------------------------------------------------
    def eth_output_dis_hnd(self):
        fx = self.output.file_open('dis-hnd')
        fempty = True
        for f in self.eth_hfpdu_ord:
            pdu = self.eth_hf[f]['pdu']
            if (pdu and pdu['reg'] and not pdu['hidden']):
                dis = self.proto
                if (pdu['reg'] != '.'):
                    dis += '.' + pdu['reg']
                fx.write('static dissector_handle_t %s_handle;\n' % (asn2c(dis)))
                fempty = False
1844
        fx.write('\n')
1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861
        self.output.file_close(fx, discard=fempty)

    #--- eth_output_dis_reg -----------------------------------------------------
    def eth_output_dis_reg(self):
        fx = self.output.file_open('dis-reg')
        fempty = True
        for f in self.eth_hfpdu_ord:
            pdu = self.eth_hf[f]['pdu']
            if (pdu and pdu['reg']):
                new_prefix = ''
                if (pdu['new']): new_prefix = 'new_'
                dis = self.proto
                if (pdu['reg'] != '.'): dis += '.' + pdu['reg']
                fx.write('  %sregister_dissector("%s", dissect_%s, proto_%s);\n' % (new_prefix, dis, f, self.eproto))
                if (not pdu['hidden']):
                    fx.write('  %s_handle = find_dissector("%s");\n' % (asn2c(dis), dis))
                fempty = False
Ronnie Sahlberg's avatar
Ronnie Sahlberg committed
1862
        fx.write('\n')
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
        self.output.file_close(fx, discard=fempty)

    #--- eth_output_dis_tab -----------------------------------------------------
    def eth_output_dis_tab(self):
        fx = self.output.file_open('dis-tab')
        fempty = True
        for k in self.conform.get_order('REGISTER'):
            reg = self.conform.use_item('REGISTER', k)
            if reg['pdu'] not in self.field: continue
            f = self.field[reg['pdu']]['ethname']
            pdu = self.eth_hf[f]['pdu']
            new_prefix = ''
            if (pdu['new']): new_prefix = 'new_'
            if (reg['rtype'] in ('NUM', 'STR')):
                rstr = ''
                if (reg['rtype'] == 'STR'):
                    rstr = 'string'
                else:
                    rstr = 'uint'
                if (pdu['reg']):
                    dis = self.proto
                    if (pdu['reg'] != '.'): dis += '.' + pdu['reg']
                    if  (not pdu['hidden']):
                        hnd = '%s_handle' % (asn2c(dis))
                    else:
                        hnd = 'find_dissector("%s")' % (dis)
                else:
                    hnd = '%screate_dissector_handle(dissect_%s, proto_%s)' % (new_prefix, f, self.eproto)
                rport = self.value_get_eth(reg['rport'])
                fx.write('  dissector_add_%s("%s", %s, %s);\n' % (rstr, reg['rtable'], rport, hnd))
            elif (reg['rtype'] in ('BER', 'PER')):
                roid = self.value_get_eth(reg['roid'])
                fx.write('  %sregister_%s_oid_dissector(%s, dissect_%s, proto_%s, %s);\n' % (new_prefix, reg['rtype'].lower(), roid, f, self.eproto, reg['roidname']))
            fempty = False
        fx.write('\n')
        self.output.file_close(fx, discard=fempty)

    #--- eth_output_syn_reg -----------------------------------------------------
    def eth_output_syn_reg(self):
        fx = self.output.file_open('syn-reg')
        fempty = True
        first_decl = True
        for k in self.conform.get_order('SYNTAX'):
            reg = self.conform.use_item('SYNTAX', k)
1907 1908 1909 1910 1911
            if reg['pdu'] not in self.field: continue
            f = self.field[reg['pdu']]['ethname']
            pdu = self.eth_hf[f]['pdu']
            new_prefix = ''
            if (pdu['new']): new_prefix = 'new_'
1912 1913 1914
            if first_decl:
                fx.write('  /*--- Syntax registrations ---*/\n')
                first_decl = False
1915
            fx.write('  %sregister_ber_syntax_dissector(%s, proto_%s, dissect_%s_PDU);\n' % (new_prefix, k, self.eproto, reg['pdu']));
1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963
            fempty=False
        self.output.file_close(fx, discard=fempty)

    #--- eth_output_tables -----------------------------------------------------
    def eth_output_tables(self):
        for num in list(self.conform.report.keys()):
            fx = self.output.file_open('table' + num)
            for rep in self.conform.report[num]:
                self.eth_output_table(fx, rep)
            self.output.file_close(fx)

    #--- eth_output_table -----------------------------------------------------
    def eth_output_table(self, fx, rep):
        if rep['type'] == 'HDR':
            fx.write('\n')
        if rep['var']:
            var = rep['var']
            var_list = var.split('.', 1)
            cls = var_list[0]
            del var_list[0]
            flds = []
            not_flds = []
            sort_flds = []
            for f in var_list:
                if f[0] == '!':
                    not_flds.append(f[1:])
                    continue
                if f[0] == '#':
                    flds.append(f[1:])
                    sort_flds.append(f)
                    continue
                if f[0] == '@':
                    flds.append(f[1:])
                    sort_flds.append(f[1:])
                    continue
                flds.append(f)
            objs = {}
            objs_ord = []
            if (cls in self.oassign_cls):
                for ident in self.oassign_cls[cls]:
                    obj = self.get_obj_repr(ident, flds, not_flds)
                    if not obj:
                        continue
                    obj['_LOOP'