Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1 | from construct.lib.containers import Container, ListContainer |
| 2 | from construct.core import EnumIntegerString |
Harald Welte | 07c7b1f | 2021-05-28 22:01:29 +0200 | [diff] [blame] | 3 | import typing |
Harald Welte | e0f9ef1 | 2021-04-10 17:22:35 +0200 | [diff] [blame] | 4 | from construct import * |
Vadim Yanitskiy | 05d30eb | 2022-08-29 20:24:44 +0700 | [diff] [blame] | 5 | from construct.core import evaluate, BitwisableString |
Harald Welte | d0519e0 | 2022-02-11 18:05:48 +0100 | [diff] [blame] | 6 | from construct.lib import integertypes |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 7 | from pySim.utils import b2h, h2b, swap_nibbles |
Robert Falkenberg | b07a3e9 | 2021-05-07 15:23:20 +0200 | [diff] [blame] | 8 | import gsm0338 |
Philipp Maier | 791f80a | 2023-07-26 17:01:37 +0200 | [diff] [blame] | 9 | import codecs |
Harald Welte | e0f9ef1 | 2021-04-10 17:22:35 +0200 | [diff] [blame] | 10 | |
| 11 | """Utility code related to the integration of the 'construct' declarative parser.""" |
| 12 | |
Harald Welte | d0519e0 | 2022-02-11 18:05:48 +0100 | [diff] [blame] | 13 | # (C) 2021-2022 by Harald Welte <laforge@osmocom.org> |
Harald Welte | e0f9ef1 | 2021-04-10 17:22:35 +0200 | [diff] [blame] | 14 | # |
| 15 | # This program is free software: you can redistribute it and/or modify |
| 16 | # it under the terms of the GNU General Public License as published by |
| 17 | # the Free Software Foundation, either version 2 of the License, or |
| 18 | # (at your option) any later version. |
| 19 | # |
| 20 | # This program is distributed in the hope that it will be useful, |
| 21 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 22 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 23 | # GNU General Public License for more details. |
| 24 | # |
| 25 | # You should have received a copy of the GNU General Public License |
| 26 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 27 | |
| 28 | |
| 29 | class HexAdapter(Adapter): |
| 30 | """convert a bytes() type to a string of hex nibbles.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 31 | |
Harald Welte | e0f9ef1 | 2021-04-10 17:22:35 +0200 | [diff] [blame] | 32 | def _decode(self, obj, context, path): |
| 33 | return b2h(obj) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 34 | |
Harald Welte | e0f9ef1 | 2021-04-10 17:22:35 +0200 | [diff] [blame] | 35 | def _encode(self, obj, context, path): |
| 36 | return h2b(obj) |
| 37 | |
Philipp Maier | 791f80a | 2023-07-26 17:01:37 +0200 | [diff] [blame] | 38 | class Utf8Adapter(Adapter): |
| 39 | """convert a bytes() type that contains utf8 encoded text to human readable text.""" |
| 40 | |
| 41 | def _decode(self, obj, context, path): |
| 42 | # In case the string contains only 0xff bytes we interpret it as an empty string |
| 43 | if obj == b'\xff' * len(obj): |
| 44 | return "" |
| 45 | return codecs.decode(obj, "utf-8") |
| 46 | |
| 47 | def _encode(self, obj, context, path): |
| 48 | return codecs.encode(obj, "utf-8") |
| 49 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 50 | |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 51 | class BcdAdapter(Adapter): |
| 52 | """convert a bytes() type to a string of BCD nibbles.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 53 | |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 54 | def _decode(self, obj, context, path): |
| 55 | return swap_nibbles(b2h(obj)) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 56 | |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 57 | def _encode(self, obj, context, path): |
| 58 | return h2b(swap_nibbles(obj)) |
| 59 | |
Harald Welte | bc0e209 | 2022-02-13 10:54:58 +0100 | [diff] [blame] | 60 | class InvertAdapter(Adapter): |
| 61 | """inverse logic (false->true, true->false).""" |
| 62 | @staticmethod |
| 63 | def _invert_bool_in_obj(obj): |
| 64 | for k,v in obj.items(): |
| 65 | # skip all private entries |
| 66 | if k.startswith('_'): |
| 67 | continue |
| 68 | if v == False: |
| 69 | obj[k] = True |
| 70 | elif v == True: |
| 71 | obj[k] = False |
| 72 | return obj |
| 73 | |
| 74 | def _decode(self, obj, context, path): |
| 75 | return self._invert_bool_in_obj(obj) |
| 76 | |
| 77 | def _encode(self, obj, context, path): |
| 78 | return self._invert_bool_in_obj(obj) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 79 | |
Robert Falkenberg | b07a3e9 | 2021-05-07 15:23:20 +0200 | [diff] [blame] | 80 | class Rpad(Adapter): |
| 81 | """ |
Harald Welte | f9a5ba5 | 2023-06-09 09:17:05 +0200 | [diff] [blame] | 82 | Encoder appends padding bytes (b'\\xff') or characters up to target size. |
| 83 | Decoder removes trailing padding bytes/characters. |
Robert Falkenberg | b07a3e9 | 2021-05-07 15:23:20 +0200 | [diff] [blame] | 84 | |
| 85 | Parameters: |
| 86 | subcon: Subconstruct as defined by construct library |
| 87 | pattern: set padding pattern (default: b'\\xff') |
Harald Welte | f9a5ba5 | 2023-06-09 09:17:05 +0200 | [diff] [blame] | 88 | num_per_byte: number of 'elements' per byte. E.g. for hex nibbles: 2 |
Robert Falkenberg | b07a3e9 | 2021-05-07 15:23:20 +0200 | [diff] [blame] | 89 | """ |
| 90 | |
Harald Welte | f9a5ba5 | 2023-06-09 09:17:05 +0200 | [diff] [blame] | 91 | def __init__(self, subcon, pattern=b'\xff', num_per_byte=1): |
Robert Falkenberg | b07a3e9 | 2021-05-07 15:23:20 +0200 | [diff] [blame] | 92 | super().__init__(subcon) |
| 93 | self.pattern = pattern |
Harald Welte | f9a5ba5 | 2023-06-09 09:17:05 +0200 | [diff] [blame] | 94 | self.num_per_byte = num_per_byte |
Robert Falkenberg | b07a3e9 | 2021-05-07 15:23:20 +0200 | [diff] [blame] | 95 | |
| 96 | def _decode(self, obj, context, path): |
| 97 | return obj.rstrip(self.pattern) |
| 98 | |
| 99 | def _encode(self, obj, context, path): |
Harald Welte | f9a5ba5 | 2023-06-09 09:17:05 +0200 | [diff] [blame] | 100 | target_size = self.sizeof() * self.num_per_byte |
| 101 | if len(obj) > target_size: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 102 | raise SizeofError("Input ({}) exceeds target size ({})".format( |
Harald Welte | f9a5ba5 | 2023-06-09 09:17:05 +0200 | [diff] [blame] | 103 | len(obj), target_size)) |
| 104 | return obj + self.pattern * (target_size - len(obj)) |
Robert Falkenberg | b07a3e9 | 2021-05-07 15:23:20 +0200 | [diff] [blame] | 105 | |
Harald Welte | 954ce95 | 2023-05-27 20:08:09 +0200 | [diff] [blame] | 106 | class MultiplyAdapter(Adapter): |
| 107 | """ |
| 108 | Decoder multiplies by multiplicator |
| 109 | Encoder divides by multiplicator |
| 110 | |
| 111 | Parameters: |
| 112 | subcon: Subconstruct as defined by construct library |
| 113 | multiplier: Multiplier to apply to raw encoded value |
| 114 | """ |
| 115 | |
| 116 | def __init__(self, subcon, multiplicator): |
| 117 | super().__init__(subcon) |
| 118 | self.multiplicator = multiplicator |
| 119 | |
| 120 | def _decode(self, obj, context, path): |
| 121 | return obj * 8 |
| 122 | |
| 123 | def _encode(self, obj, context, path): |
| 124 | return obj // 8 |
| 125 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 126 | |
Robert Falkenberg | b07a3e9 | 2021-05-07 15:23:20 +0200 | [diff] [blame] | 127 | class GsmStringAdapter(Adapter): |
| 128 | """Convert GSM 03.38 encoded bytes to a string.""" |
| 129 | |
| 130 | def __init__(self, subcon, codec='gsm03.38', err='strict'): |
| 131 | super().__init__(subcon) |
| 132 | self.codec = codec |
| 133 | self.err = err |
| 134 | |
| 135 | def _decode(self, obj, context, path): |
| 136 | return obj.decode(self.codec) |
| 137 | |
| 138 | def _encode(self, obj, context, path): |
| 139 | return obj.encode(self.codec, self.err) |
| 140 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 141 | |
Harald Welte | e0f9ef1 | 2021-04-10 17:22:35 +0200 | [diff] [blame] | 142 | def filter_dict(d, exclude_prefix='_'): |
| 143 | """filter the input dict to ensure no keys starting with 'exclude_prefix' remain.""" |
Harald Welte | 7fca85b | 2021-05-29 21:27:46 +0200 | [diff] [blame] | 144 | if not isinstance(d, dict): |
| 145 | return d |
Harald Welte | e0f9ef1 | 2021-04-10 17:22:35 +0200 | [diff] [blame] | 146 | res = {} |
| 147 | for (key, value) in d.items(): |
| 148 | if key.startswith(exclude_prefix): |
| 149 | continue |
| 150 | if type(value) is dict: |
| 151 | res[key] = filter_dict(value) |
| 152 | else: |
| 153 | res[key] = value |
| 154 | return res |
| 155 | |
Harald Welte | 07c7b1f | 2021-05-28 22:01:29 +0200 | [diff] [blame] | 156 | |
| 157 | def normalize_construct(c): |
| 158 | """Convert a construct specific type to a related base type, mostly useful |
| 159 | so we can serialize it.""" |
| 160 | # we need to include the filter_dict as we otherwise get elements like this |
| 161 | # in the dict: '_io': <_io.BytesIO object at 0x7fdb64e05860> which we cannot json-serialize |
| 162 | c = filter_dict(c) |
| 163 | if isinstance(c, Container) or isinstance(c, dict): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 164 | r = {k: normalize_construct(v) for (k, v) in c.items()} |
Harald Welte | 07c7b1f | 2021-05-28 22:01:29 +0200 | [diff] [blame] | 165 | elif isinstance(c, ListContainer): |
| 166 | r = [normalize_construct(x) for x in c] |
| 167 | elif isinstance(c, list): |
| 168 | r = [normalize_construct(x) for x in c] |
| 169 | elif isinstance(c, EnumIntegerString): |
| 170 | r = str(c) |
| 171 | else: |
| 172 | r = c |
| 173 | return r |
| 174 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 175 | |
| 176 | def parse_construct(c, raw_bin_data: bytes, length: typing.Optional[int] = None, exclude_prefix: str = '_'): |
Harald Welte | 07c7b1f | 2021-05-28 22:01:29 +0200 | [diff] [blame] | 177 | """Helper function to wrap around normalize_construct() and filter_dict().""" |
| 178 | if not length: |
| 179 | length = len(raw_bin_data) |
| 180 | parsed = c.parse(raw_bin_data, total_len=length) |
| 181 | return normalize_construct(parsed) |
| 182 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 183 | |
Harald Welte | e0f9ef1 | 2021-04-10 17:22:35 +0200 | [diff] [blame] | 184 | # here we collect some shared / common definitions of data types |
| 185 | LV = Prefixed(Int8ub, HexAdapter(GreedyBytes)) |
Robert Falkenberg | 9d16fbc | 2021-04-12 11:43:22 +0200 | [diff] [blame] | 186 | |
| 187 | # Default value for Reserved for Future Use (RFU) bits/bytes |
| 188 | # See TS 31.101 Sec. "3.4 Coding Conventions" |
| 189 | __RFU_VALUE = 0 |
| 190 | |
| 191 | # Field that packs Reserved for Future Use (RFU) bit |
| 192 | FlagRFU = Default(Flag, __RFU_VALUE) |
| 193 | |
| 194 | # Field that packs Reserved for Future Use (RFU) byte |
| 195 | ByteRFU = Default(Byte, __RFU_VALUE) |
| 196 | |
| 197 | # Field that packs all remaining Reserved for Future Use (RFU) bytes |
| 198 | GreedyBytesRFU = Default(GreedyBytes, b'') |
| 199 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 200 | |
Robert Falkenberg | 9d16fbc | 2021-04-12 11:43:22 +0200 | [diff] [blame] | 201 | def BitsRFU(n=1): |
| 202 | ''' |
| 203 | Field that packs Reserved for Future Use (RFU) bit(s) |
| 204 | as defined in TS 31.101 Sec. "3.4 Coding Conventions" |
| 205 | |
| 206 | Use this for (currently) unused/reserved bits whose contents |
| 207 | should be initialized automatically but should not be cleared |
| 208 | in the future or when restoring read data (unlike padding). |
| 209 | |
| 210 | Parameters: |
| 211 | n (Integer): Number of bits (default: 1) |
| 212 | ''' |
| 213 | return Default(BitsInteger(n), __RFU_VALUE) |
| 214 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 215 | |
Robert Falkenberg | 9d16fbc | 2021-04-12 11:43:22 +0200 | [diff] [blame] | 216 | def BytesRFU(n=1): |
| 217 | ''' |
| 218 | Field that packs Reserved for Future Use (RFU) byte(s) |
| 219 | as defined in TS 31.101 Sec. "3.4 Coding Conventions" |
| 220 | |
| 221 | Use this for (currently) unused/reserved bytes whose contents |
| 222 | should be initialized automatically but should not be cleared |
| 223 | in the future or when restoring read data (unlike padding). |
| 224 | |
| 225 | Parameters: |
| 226 | n (Integer): Number of bytes (default: 1) |
| 227 | ''' |
| 228 | return Default(Bytes(n), __RFU_VALUE) |
Robert Falkenberg | b07a3e9 | 2021-05-07 15:23:20 +0200 | [diff] [blame] | 229 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 230 | |
Robert Falkenberg | b07a3e9 | 2021-05-07 15:23:20 +0200 | [diff] [blame] | 231 | def GsmString(n): |
| 232 | ''' |
| 233 | GSM 03.38 encoded byte string of fixed length n. |
| 234 | Encoder appends padding bytes (b'\\xff') to maintain |
| 235 | length. Decoder removes those trailing bytes. |
| 236 | |
| 237 | Exceptions are raised for invalid characters |
| 238 | and length excess. |
| 239 | |
| 240 | Parameters: |
| 241 | n (Integer): Fixed length of the encoded byte string |
| 242 | ''' |
| 243 | return GsmStringAdapter(Rpad(Bytes(n), pattern=b'\xff'), codec='gsm03.38') |
Harald Welte | d0519e0 | 2022-02-11 18:05:48 +0100 | [diff] [blame] | 244 | |
| 245 | class GreedyInteger(Construct): |
| 246 | """A variable-length integer implementation, think of combining GrredyBytes with BytesInteger.""" |
Philipp Maier | 541a915 | 2022-06-01 18:21:17 +0200 | [diff] [blame] | 247 | def __init__(self, signed=False, swapped=False, minlen=0): |
Harald Welte | d0519e0 | 2022-02-11 18:05:48 +0100 | [diff] [blame] | 248 | super().__init__() |
| 249 | self.signed = signed |
| 250 | self.swapped = swapped |
Philipp Maier | 541a915 | 2022-06-01 18:21:17 +0200 | [diff] [blame] | 251 | self.minlen = minlen |
Harald Welte | d0519e0 | 2022-02-11 18:05:48 +0100 | [diff] [blame] | 252 | |
| 253 | def _parse(self, stream, context, path): |
| 254 | data = stream_read_entire(stream, path) |
| 255 | if evaluate(self.swapped, context): |
| 256 | data = swapbytes(data) |
| 257 | try: |
Vadim Yanitskiy | 05d30eb | 2022-08-29 20:24:44 +0700 | [diff] [blame] | 258 | return int.from_bytes(data, byteorder='big', signed=self.signed) |
Harald Welte | d0519e0 | 2022-02-11 18:05:48 +0100 | [diff] [blame] | 259 | except ValueError as e: |
| 260 | raise IntegerError(str(e), path=path) |
| 261 | |
Philipp Maier | 541a915 | 2022-06-01 18:21:17 +0200 | [diff] [blame] | 262 | def __bytes_required(self, i, minlen=0): |
Harald Welte | d0519e0 | 2022-02-11 18:05:48 +0100 | [diff] [blame] | 263 | if self.signed: |
| 264 | raise NotImplementedError("FIXME: Implement support for encoding signed integer") |
Philipp Maier | 541a915 | 2022-06-01 18:21:17 +0200 | [diff] [blame] | 265 | |
| 266 | # compute how many bytes we need |
Harald Welte | d0519e0 | 2022-02-11 18:05:48 +0100 | [diff] [blame] | 267 | nbytes = 1 |
| 268 | while True: |
| 269 | i = i >> 8 |
| 270 | if i == 0: |
Philipp Maier | 541a915 | 2022-06-01 18:21:17 +0200 | [diff] [blame] | 271 | break |
Harald Welte | d0519e0 | 2022-02-11 18:05:48 +0100 | [diff] [blame] | 272 | else: |
| 273 | nbytes = nbytes + 1 |
Philipp Maier | 541a915 | 2022-06-01 18:21:17 +0200 | [diff] [blame] | 274 | |
| 275 | # round up to the minimum number |
| 276 | # of bytes we anticipate |
| 277 | if nbytes < minlen: |
| 278 | nbytes = minlen |
| 279 | |
| 280 | return nbytes |
Harald Welte | d0519e0 | 2022-02-11 18:05:48 +0100 | [diff] [blame] | 281 | |
| 282 | def _build(self, obj, stream, context, path): |
| 283 | if not isinstance(obj, integertypes): |
| 284 | raise IntegerError(f"value {obj} is not an integer", path=path) |
Philipp Maier | 541a915 | 2022-06-01 18:21:17 +0200 | [diff] [blame] | 285 | length = self.__bytes_required(obj, self.minlen) |
Harald Welte | d0519e0 | 2022-02-11 18:05:48 +0100 | [diff] [blame] | 286 | try: |
Vadim Yanitskiy | 05d30eb | 2022-08-29 20:24:44 +0700 | [diff] [blame] | 287 | data = obj.to_bytes(length, byteorder='big', signed=self.signed) |
Harald Welte | d0519e0 | 2022-02-11 18:05:48 +0100 | [diff] [blame] | 288 | except ValueError as e: |
| 289 | raise IntegerError(str(e), path=path) |
| 290 | if evaluate(self.swapped, context): |
| 291 | data = swapbytes(data) |
| 292 | stream_write(stream, data, length, path) |
| 293 | return obj |
Harald Welte | bc0e209 | 2022-02-13 10:54:58 +0100 | [diff] [blame] | 294 | |
| 295 | # merged definitions of 24.008 + 23.040 |
| 296 | TypeOfNumber = Enum(BitsInteger(3), unknown=0, international=1, national=2, network_specific=3, |
| 297 | short_code=4, alphanumeric=5, abbreviated=6, reserved_for_extension=7) |
| 298 | NumberingPlan = Enum(BitsInteger(4), unknown=0, isdn_e164=1, data_x121=3, telex_f69=4, |
| 299 | sc_specific_5=5, sc_specific_6=6, national=8, private=9, |
| 300 | ermes=10, reserved_cts=11, reserved_for_extension=15) |
| 301 | TonNpi = BitStruct('ext'/Flag, 'type_of_number'/TypeOfNumber, 'numbering_plan_id'/NumberingPlan) |