Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 1 | """object-oriented TLV parser/encoder library.""" |
| 2 | |
| 3 | # (C) 2021 by Harald Welte <laforge@osmocom.org> |
| 4 | # All Rights Reserved |
| 5 | # |
| 6 | # This program is free software: you can redistribute it and/or modify |
| 7 | # it under the terms of the GNU General Public License as published by |
| 8 | # the Free Software Foundation, either version 2 of the License, or |
| 9 | # (at your option) any later version. |
| 10 | # |
| 11 | # This program is distributed in the hope that it will be useful, |
| 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 | # GNU General Public License for more details. |
| 15 | # |
| 16 | # You should have received a copy of the GNU General Public License |
| 17 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 18 | |
| 19 | |
| 20 | from typing import Optional, List, Dict, Any, Tuple |
| 21 | from bidict import bidict |
| 22 | from construct import * |
| 23 | |
| 24 | from pySim.utils import bertlv_encode_len, bertlv_parse_len, bertlv_encode_tag, bertlv_parse_tag |
| 25 | from pySim.utils import comprehensiontlv_encode_tag, comprehensiontlv_parse_tag |
| 26 | from pySim.utils import bertlv_parse_one, comprehensiontlv_parse_one |
| 27 | from pySim.utils import bertlv_parse_tag_raw, comprehensiontlv_parse_tag_raw |
| 28 | |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 29 | from pySim.construct import build_construct, parse_construct, LV, HexAdapter, BcdAdapter, BitsRFU, GsmStringAdapter |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 30 | from pySim.exceptions import * |
| 31 | |
| 32 | import inspect |
| 33 | import abc |
Harald Welte | e8d177d | 2022-02-11 17:08:45 +0100 | [diff] [blame] | 34 | import re |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 35 | |
Harald Welte | e8d177d | 2022-02-11 17:08:45 +0100 | [diff] [blame] | 36 | def camel_to_snake(name): |
| 37 | name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) |
| 38 | return re.sub('([a-z0-9])([A-Z])', r'\1_\2', name).lower() |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 39 | |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 40 | class TlvMeta(abc.ABCMeta): |
| 41 | """Metaclass which we use to set some class variables at the time of defining a subclass. |
| 42 | This allows us to create subclasses for each TLV/IE type, where the class represents fixed |
| 43 | parameters like the tag/type and instances of it represent the actual TLV data.""" |
| 44 | def __new__(metacls, name, bases, namespace, **kwargs): |
| 45 | #print("TlvMeta_new_(metacls=%s, name=%s, bases=%s, namespace=%s, kwargs=%s)" % (metacls, name, bases, namespace, kwargs)) |
| 46 | x = super().__new__(metacls, name, bases, namespace) |
| 47 | # this becomes a _class_ variable, not an instance variable |
| 48 | x.tag = namespace.get('tag', kwargs.get('tag', None)) |
| 49 | x.desc = namespace.get('desc', kwargs.get('desc', None)) |
| 50 | nested = namespace.get('nested', kwargs.get('nested', None)) |
| 51 | if nested is None or inspect.isclass(nested) and issubclass(nested, TLV_IE_Collection): |
| 52 | # caller has specified TLV_IE_Collection sub-class, we can directly reference it |
| 53 | x.nested_collection_cls = nested |
| 54 | else: |
| 55 | # caller passed list of other TLV classes that might possibly appear within us, |
| 56 | # build a dynamically-created TLV_IE_Collection sub-class and reference it |
| 57 | name = 'auto_collection_%s' % (name) |
| 58 | cls = type(name, (TLV_IE_Collection,), {'nested': nested}) |
| 59 | x.nested_collection_cls = cls |
| 60 | return x |
| 61 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 62 | |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 63 | class TlvCollectionMeta(abc.ABCMeta): |
| 64 | """Metaclass which we use to set some class variables at the time of defining a subclass. |
| 65 | This allows us to create subclasses for each Collection type, where the class represents fixed |
| 66 | parameters like the nested IE classes and instances of it represent the actual TLV data.""" |
| 67 | def __new__(metacls, name, bases, namespace, **kwargs): |
| 68 | #print("TlvCollectionMeta_new_(metacls=%s, name=%s, bases=%s, namespace=%s, kwargs=%s)" % (metacls, name, bases, namespace, kwargs)) |
| 69 | x = super().__new__(metacls, name, bases, namespace) |
| 70 | # this becomes a _class_ variable, not an instance variable |
| 71 | x.possible_nested = namespace.get('nested', kwargs.get('nested', None)) |
| 72 | return x |
| 73 | |
| 74 | |
| 75 | class Transcodable(abc.ABC): |
| 76 | _construct = None |
| 77 | """Base class for something that can be encoded + encoded. Decoding and Encoding happens either |
| 78 | * via a 'construct' object stored in a derived class' _construct variable, or |
| 79 | * via a 'construct' object stored in an instance _construct variable, or |
| 80 | * via a derived class' _{to,from}_bytes() methods.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 81 | |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 82 | def __init__(self): |
| 83 | self.encoded = None |
| 84 | self.decoded = None |
| 85 | self._construct = None |
| 86 | |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 87 | def to_bytes(self, context: dict = {}) -> bytes: |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 88 | """Convert from internal representation to binary bytes. Store the binary result |
| 89 | in the internal state and return it.""" |
Harald Welte | 0f7d48e | 2023-12-06 23:56:28 +0100 | [diff] [blame] | 90 | if self.decoded == None: |
Harald Welte | 04c1302 | 2021-10-21 10:02:10 +0200 | [diff] [blame] | 91 | do = b'' |
| 92 | elif self._construct: |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 93 | do = build_construct(self._construct, self.decoded, context) |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 94 | elif self.__class__._construct: |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 95 | do = build_construct(self.__class__._construct, self.decoded, context) |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 96 | else: |
| 97 | do = self._to_bytes() |
| 98 | self.encoded = do |
| 99 | return do |
| 100 | |
| 101 | # not an abstractmethod, as it is only required if no _construct exists |
| 102 | def _to_bytes(self): |
Harald Welte | ea600a8 | 2022-07-20 07:51:13 +0200 | [diff] [blame] | 103 | raise NotImplementedError('%s._to_bytes' % type(self).__name__) |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 104 | |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 105 | def from_bytes(self, do: bytes, context: dict = {}): |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 106 | """Convert from binary bytes to internal representation. Store the decoded result |
| 107 | in the internal state and return it.""" |
| 108 | self.encoded = do |
Harald Welte | 04c1302 | 2021-10-21 10:02:10 +0200 | [diff] [blame] | 109 | if self.encoded == b'': |
| 110 | self.decoded = None |
| 111 | elif self._construct: |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 112 | self.decoded = parse_construct(self._construct, do, context=context) |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 113 | elif self.__class__._construct: |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 114 | self.decoded = parse_construct(self.__class__._construct, do, context=context) |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 115 | else: |
| 116 | self.decoded = self._from_bytes(do) |
| 117 | return self.decoded |
| 118 | |
| 119 | # not an abstractmethod, as it is only required if no _construct exists |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 120 | def _from_bytes(self, do: bytes): |
Harald Welte | ea600a8 | 2022-07-20 07:51:13 +0200 | [diff] [blame] | 121 | raise NotImplementedError('%s._from_bytes' % type(self).__name__) |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 122 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 123 | |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 124 | class IE(Transcodable, metaclass=TlvMeta): |
| 125 | # we specify the metaclass so any downstream subclasses will automatically use it |
| 126 | """Base class for various Information Elements. We understand the notion of a hierarchy |
| 127 | of IEs on top of the Transcodable class.""" |
| 128 | # this is overridden by the TlvMeta metaclass, if it is used to create subclasses |
| 129 | nested_collection_cls = None |
| 130 | tag = None |
| 131 | |
| 132 | def __init__(self, **kwargs): |
| 133 | super().__init__() |
| 134 | self.nested_collection = None |
| 135 | if self.nested_collection_cls: |
| 136 | self.nested_collection = self.nested_collection_cls() |
| 137 | # if we are a constructed IE, [ordered] list of actual child-IE instances |
| 138 | self.children = kwargs.get('children', []) |
| 139 | self.decoded = kwargs.get('decoded', None) |
| 140 | |
| 141 | def __repr__(self): |
| 142 | """Return a string representing the [nested] IE data (for print).""" |
| 143 | if len(self.children): |
| 144 | member_strs = [repr(x) for x in self.children] |
| 145 | return '%s(%s)' % (type(self).__name__, ','.join(member_strs)) |
| 146 | else: |
| 147 | return '%s(%s)' % (type(self).__name__, self.decoded) |
| 148 | |
| 149 | def to_dict(self): |
| 150 | """Return a JSON-serializable dict representing the [nested] IE data.""" |
| 151 | if len(self.children): |
| 152 | v = [x.to_dict() for x in self.children] |
| 153 | else: |
| 154 | v = self.decoded |
Harald Welte | e8d177d | 2022-02-11 17:08:45 +0100 | [diff] [blame] | 155 | return {camel_to_snake(type(self).__name__): v} |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 156 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 157 | def from_dict(self, decoded: dict): |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 158 | """Set the IE internal decoded representation to data from the argument. |
| 159 | If this is a nested IE, the child IE instance list is re-created.""" |
Harald Welte | a9b21bd | 2023-12-27 15:52:11 +0100 | [diff] [blame] | 160 | expected_key_name = camel_to_snake(type(self).__name__) |
| 161 | if not expected_key_name in decoded: |
| 162 | raise ValueError("Dict %s doesn't contain expected key %s" % (decoded, expected_key_name)) |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 163 | if self.nested_collection: |
Harald Welte | a9b21bd | 2023-12-27 15:52:11 +0100 | [diff] [blame] | 164 | self.children = self.nested_collection.from_dict(decoded[expected_key_name]) |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 165 | else: |
| 166 | self.children = [] |
Harald Welte | 579ac3e | 2023-06-26 10:52:19 +0200 | [diff] [blame] | 167 | self.decoded = decoded[expected_key_name] |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 168 | |
| 169 | def is_constructed(self): |
| 170 | """Is this IE constructed by further nested IEs?""" |
| 171 | if len(self.children): |
| 172 | return True |
| 173 | else: |
| 174 | return False |
| 175 | |
| 176 | @abc.abstractmethod |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 177 | def to_ie(self, context: dict = {}) -> bytes: |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 178 | """Convert the internal representation to entire IE including IE header.""" |
| 179 | |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 180 | def to_bytes(self, context: dict = {}) -> bytes: |
Harald Welte | 6663218 | 2023-11-01 17:28:18 +0100 | [diff] [blame] | 181 | """Convert the internal representation *of the value part* to binary bytes.""" |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 182 | if self.is_constructed(): |
| 183 | # concatenate the encoded IE of all children to form the value part |
| 184 | out = b'' |
| 185 | for c in self.children: |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 186 | out += c.to_ie(context=context) |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 187 | return out |
| 188 | else: |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 189 | return super().to_bytes(context=context) |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 190 | |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 191 | def from_bytes(self, do: bytes, context: dict = {}): |
Harald Welte | 6663218 | 2023-11-01 17:28:18 +0100 | [diff] [blame] | 192 | """Parse *the value part* from binary bytes to internal representation.""" |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 193 | if self.nested_collection: |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 194 | self.children = self.nested_collection.from_bytes(do, context=context) |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 195 | else: |
| 196 | self.children = [] |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 197 | return super().from_bytes(do, context=context) |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 198 | |
| 199 | |
| 200 | class TLV_IE(IE): |
| 201 | """Abstract base class for various TLV type Information Elements.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 202 | |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 203 | def __init__(self, **kwargs): |
| 204 | super().__init__(**kwargs) |
| 205 | |
| 206 | def _compute_tag(self) -> int: |
| 207 | """Compute the tag (sometimes the tag encodes part of the value).""" |
| 208 | return self.tag |
| 209 | |
| 210 | @classmethod |
| 211 | @abc.abstractmethod |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 212 | def _parse_tag_raw(cls, do: bytes) -> Tuple[int, bytes]: |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 213 | """Obtain the raw TAG at the start of the bytes provided by the user.""" |
| 214 | |
| 215 | @classmethod |
| 216 | @abc.abstractmethod |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 217 | def _parse_len(cls, do: bytes) -> Tuple[int, bytes]: |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 218 | """Obtain the length encoded at the start of the bytes provided by the user.""" |
| 219 | |
| 220 | @abc.abstractmethod |
| 221 | def _encode_tag(self) -> bytes: |
| 222 | """Encode the tag part. Must be provided by derived (TLV format specific) class.""" |
| 223 | |
| 224 | @abc.abstractmethod |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 225 | def _encode_len(self, val: bytes) -> bytes: |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 226 | """Encode the length part assuming a certain binary value. Must be provided by |
| 227 | derived (TLV format specific) class.""" |
| 228 | |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 229 | def to_ie(self, context: dict = {}): |
| 230 | return self.to_tlv(context=context) |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 231 | |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 232 | def to_tlv(self, context: dict = {}): |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 233 | """Convert the internal representation to binary TLV bytes.""" |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 234 | val = self.to_bytes(context=context) |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 235 | return self._encode_tag() + self._encode_len(val) + val |
| 236 | |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 237 | def from_tlv(self, do: bytes, context: dict = {}): |
Harald Welte | e4a6eaf | 2022-02-11 16:29:32 +0100 | [diff] [blame] | 238 | if len(do) == 0: |
| 239 | return {}, b'' |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 240 | (rawtag, remainder) = self.__class__._parse_tag_raw(do) |
| 241 | if rawtag: |
Harald Welte | 7d8029e | 2022-08-06 13:16:19 +0200 | [diff] [blame] | 242 | if rawtag != self._compute_tag(): |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 243 | raise ValueError("%s: Encountered tag %s doesn't match our supported tag %s" % |
| 244 | (self, rawtag, self.tag)) |
| 245 | (length, remainder) = self.__class__._parse_len(remainder) |
| 246 | value = remainder[:length] |
| 247 | remainder = remainder[length:] |
| 248 | else: |
| 249 | value = do |
| 250 | remainder = b'' |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 251 | dec = self.from_bytes(value, context=context) |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 252 | return dec, remainder |
| 253 | |
| 254 | |
| 255 | class BER_TLV_IE(TLV_IE): |
| 256 | """TLV_IE formatted as ASN.1 BER described in ITU-T X.690 8.1.2.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 257 | |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 258 | def __init__(self, **kwargs): |
| 259 | super().__init__(**kwargs) |
| 260 | |
| 261 | @classmethod |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 262 | def _decode_tag(cls, do: bytes) -> Tuple[dict, bytes]: |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 263 | return bertlv_parse_tag(do) |
| 264 | |
| 265 | @classmethod |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 266 | def _parse_tag_raw(cls, do: bytes) -> Tuple[int, bytes]: |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 267 | return bertlv_parse_tag_raw(do) |
| 268 | |
| 269 | @classmethod |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 270 | def _parse_len(cls, do: bytes) -> Tuple[int, bytes]: |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 271 | return bertlv_parse_len(do) |
| 272 | |
| 273 | def _encode_tag(self) -> bytes: |
| 274 | return bertlv_encode_tag(self._compute_tag()) |
| 275 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 276 | def _encode_len(self, val: bytes) -> bytes: |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 277 | return bertlv_encode_len(len(val)) |
| 278 | |
| 279 | |
| 280 | class COMPR_TLV_IE(TLV_IE): |
| 281 | """TLV_IE formated as COMPREHENSION-TLV as described in ETSI TS 101 220.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 282 | |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 283 | def __init__(self, **kwargs): |
| 284 | super().__init__(**kwargs) |
| 285 | self.comprehension = False |
| 286 | |
| 287 | @classmethod |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 288 | def _decode_tag(cls, do: bytes) -> Tuple[dict, bytes]: |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 289 | return comprehensiontlv_parse_tag(do) |
| 290 | |
| 291 | @classmethod |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 292 | def _parse_tag_raw(cls, do: bytes) -> Tuple[int, bytes]: |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 293 | return comprehensiontlv_parse_tag_raw(do) |
| 294 | |
| 295 | @classmethod |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 296 | def _parse_len(cls, do: bytes) -> Tuple[int, bytes]: |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 297 | return bertlv_parse_len(do) |
| 298 | |
| 299 | def _encode_tag(self) -> bytes: |
| 300 | return comprehensiontlv_encode_tag(self._compute_tag()) |
| 301 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 302 | def _encode_len(self, val: bytes) -> bytes: |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 303 | return bertlv_encode_len(len(val)) |
| 304 | |
| 305 | |
| 306 | class TLV_IE_Collection(metaclass=TlvCollectionMeta): |
| 307 | # we specify the metaclass so any downstream subclasses will automatically use it |
| 308 | """A TLV_IE_Collection consists of multiple TLV_IE classes identified by their tags. |
| 309 | A given encoded DO may contain any of them in any order, and may contain multiple instances |
| 310 | of each DO.""" |
| 311 | # this is overridden by the TlvCollectionMeta metaclass, if it is used to create subclasses |
| 312 | possible_nested = [] |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 313 | |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 314 | def __init__(self, desc=None, **kwargs): |
| 315 | self.desc = desc |
| 316 | #print("possible_nested: ", self.possible_nested) |
| 317 | self.members = kwargs.get('nested', self.possible_nested) |
| 318 | self.members_by_tag = {} |
| 319 | self.members_by_name = {} |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 320 | self.members_by_tag = {m.tag: m for m in self.members} |
Harald Welte | 30de9fd | 2023-07-09 21:25:14 +0200 | [diff] [blame] | 321 | self.members_by_name = {camel_to_snake(m.__name__): m for m in self.members} |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 322 | # if we are a constructed IE, [ordered] list of actual child-IE instances |
| 323 | self.children = kwargs.get('children', []) |
| 324 | self.encoded = None |
| 325 | |
| 326 | def __str__(self): |
| 327 | member_strs = [str(x) for x in self.members] |
| 328 | return '%s(%s)' % (type(self).__name__, ','.join(member_strs)) |
| 329 | |
| 330 | def __repr__(self): |
| 331 | member_strs = [repr(x) for x in self.members] |
| 332 | return '%s(%s)' % (self.__class__, ','.join(member_strs)) |
| 333 | |
| 334 | def __add__(self, other): |
| 335 | """Extending TLV_IE_Collections with other TLV_IE_Collections or TLV_IEs.""" |
| 336 | if isinstance(other, TLV_IE_Collection): |
| 337 | # adding one collection to another |
| 338 | members = self.members + other.members |
| 339 | return TLV_IE_Collection(self.desc, nested=members) |
| 340 | elif inspect.isclass(other) and issubclass(other, TLV_IE): |
| 341 | # adding a member to a collection |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 342 | return TLV_IE_Collection(self.desc, nested=self.members + [other]) |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 343 | else: |
| 344 | raise TypeError |
| 345 | |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 346 | def from_bytes(self, binary: bytes, context: dict = {}) -> List[TLV_IE]: |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 347 | """Create a list of TLV_IEs from the collection based on binary input data. |
| 348 | Args: |
| 349 | binary : binary bytes of encoded data |
| 350 | Returns: |
| 351 | list of instances of TLV_IE sub-classes containing parsed data |
| 352 | """ |
| 353 | self.encoded = binary |
| 354 | # list of instances of TLV_IE collection member classes appearing in the data |
| 355 | res = [] |
| 356 | remainder = binary |
| 357 | first = next(iter(self.members_by_tag.values())) |
| 358 | # iterate until no binary trailer is left |
| 359 | while len(remainder): |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 360 | context['siblings'] = res |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 361 | # obtain the tag at the start of the remainder |
| 362 | tag, r = first._parse_tag_raw(remainder) |
Harald Welte | fb50621 | 2021-05-29 21:28:24 +0200 | [diff] [blame] | 363 | if tag == None: |
Harald Welte | 69bdcf5 | 2023-12-28 09:21:17 +0100 | [diff] [blame] | 364 | break |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 365 | if tag in self.members_by_tag: |
| 366 | cls = self.members_by_tag[tag] |
| 367 | # create an instance and parse accordingly |
| 368 | inst = cls() |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 369 | dec, remainder = inst.from_tlv(remainder, context=context) |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 370 | res.append(inst) |
| 371 | else: |
| 372 | # unknown tag; create the related class on-the-fly using the same base class |
| 373 | name = 'unknown_%s_%X' % (first.__base__.__name__, tag) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 374 | cls = type(name, (first.__base__,), {'tag': tag, 'possible_nested': [], |
| 375 | 'nested_collection_cls': None}) |
| 376 | cls._from_bytes = lambda s, a: {'raw': a.hex()} |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 377 | cls._to_bytes = lambda s: bytes.fromhex(s.decoded['raw']) |
| 378 | # create an instance and parse accordingly |
| 379 | inst = cls() |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 380 | dec, remainder = inst.from_tlv(remainder, context=context) |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 381 | res.append(inst) |
| 382 | self.children = res |
| 383 | return res |
| 384 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 385 | def from_dict(self, decoded: List[dict]) -> List[TLV_IE]: |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 386 | """Create a list of TLV_IE instances from the collection based on an array |
| 387 | of dicts, where they key indicates the name of the TLV_IE subclass to use.""" |
| 388 | # list of instances of TLV_IE collection member classes appearing in the data |
| 389 | res = [] |
Harald Welte | 2352f2d | 2023-07-09 21:28:13 +0200 | [diff] [blame] | 390 | # iterate over members of the list passed into "decoded" |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 391 | for i in decoded: |
Harald Welte | 2352f2d | 2023-07-09 21:28:13 +0200 | [diff] [blame] | 392 | # iterate over all the keys (typically one!) within the current list item dict |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 393 | for k in i.keys(): |
Harald Welte | 2352f2d | 2023-07-09 21:28:13 +0200 | [diff] [blame] | 394 | # check if we have a member identified by the dict key |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 395 | if k in self.members_by_name: |
Harald Welte | 2352f2d | 2023-07-09 21:28:13 +0200 | [diff] [blame] | 396 | # resolve the class for that name; create an instance of it |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 397 | cls = self.members_by_name[k] |
Harald Welte | 5895380 | 2021-10-21 11:33:44 +0200 | [diff] [blame] | 398 | inst = cls() |
Harald Welte | 2352f2d | 2023-07-09 21:28:13 +0200 | [diff] [blame] | 399 | if cls.nested_collection_cls: |
| 400 | # in case of collections, we want to pass the raw "value" portion to from_dict, |
| 401 | # as to_dict() below intentionally omits the collection-class-name as key |
| 402 | inst.from_dict(i[k]) |
| 403 | else: |
| 404 | inst.from_dict({k: i[k]}) |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 405 | res.append(inst) |
| 406 | else: |
| 407 | raise ValueError('%s: Unknown TLV Class %s in %s; expected %s' % |
Harald Welte | ba955b6 | 2023-07-09 21:27:07 +0200 | [diff] [blame] | 408 | (self, k, decoded, self.members_by_name.keys())) |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 409 | self.children = res |
| 410 | return res |
| 411 | |
| 412 | def to_dict(self): |
Harald Welte | 2352f2d | 2023-07-09 21:28:13 +0200 | [diff] [blame] | 413 | # we intentionally return not a dict, but a list of dicts. We could prefix by |
| 414 | # self.__class__.__name__, but that is usually some meaningless auto-generated collection name. |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 415 | return [x.to_dict() for x in self.children] |
| 416 | |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 417 | def to_bytes(self, context: dict = {}): |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 418 | out = b'' |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 419 | context['siblings'] = self.children |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 420 | for c in self.children: |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 421 | out += c.to_tlv(context=context) |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 422 | return out |
| 423 | |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 424 | def from_tlv(self, do, context: dict = {}): |
| 425 | return self.from_bytes(do, context=context) |
Harald Welte | bb3b5df | 2021-05-24 23:15:54 +0200 | [diff] [blame] | 426 | |
Harald Welte | caef0df | 2023-12-17 10:07:01 +0100 | [diff] [blame] | 427 | def to_tlv(self, context: dict = {}): |
| 428 | return self.to_bytes(context=context) |
Harald Welte | 9a2a669 | 2022-02-11 15:44:28 +0100 | [diff] [blame] | 429 | |
| 430 | |
| 431 | def flatten_dict_lists(inp): |
| 432 | """hierarchically flatten each list-of-dicts into a single dict. This is useful to |
| 433 | make the output of hierarchical TLV decoder structures flatter and more easy to read.""" |
| 434 | def are_all_elements_dict(l): |
| 435 | for e in l: |
| 436 | if not isinstance(e, dict): |
| 437 | return False |
| 438 | return True |
| 439 | |
Harald Welte | 880db37 | 2023-12-06 09:01:00 +0100 | [diff] [blame] | 440 | def are_elements_unique(lod): |
| 441 | set_of_keys = set([list(x.keys())[0] for x in lod]) |
| 442 | return len(lod) == len(set_of_keys) |
| 443 | |
Harald Welte | 9a2a669 | 2022-02-11 15:44:28 +0100 | [diff] [blame] | 444 | if isinstance(inp, list): |
Harald Welte | 880db37 | 2023-12-06 09:01:00 +0100 | [diff] [blame] | 445 | if are_all_elements_dict(inp) and are_elements_unique(inp): |
Harald Welte | 9a2a669 | 2022-02-11 15:44:28 +0100 | [diff] [blame] | 446 | # flatten into one shared dict |
| 447 | newdict = {} |
| 448 | for e in inp: |
| 449 | key = list(e.keys())[0] |
| 450 | newdict[key] = e[key] |
| 451 | inp = newdict |
| 452 | # process result as any native dict |
| 453 | return {k:flatten_dict_lists(inp[k]) for k in inp.keys()} |
| 454 | else: |
| 455 | return [flatten_dict_lists(x) for x in inp] |
| 456 | elif isinstance(inp, dict): |
| 457 | return {k:flatten_dict_lists(inp[k]) for k in inp.keys()} |
| 458 | else: |
| 459 | return inp |