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 * |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 5 | from pySim.utils import b2h, h2b, swap_nibbles |
Robert Falkenberg | b07a3e9 | 2021-05-07 15:23:20 +0200 | [diff] [blame] | 6 | import gsm0338 |
Harald Welte | e0f9ef1 | 2021-04-10 17:22:35 +0200 | [diff] [blame] | 7 | |
| 8 | """Utility code related to the integration of the 'construct' declarative parser.""" |
| 9 | |
| 10 | # (C) 2021 by Harald Welte <laforge@osmocom.org> |
| 11 | # |
| 12 | # This program is free software: you can redistribute it and/or modify |
| 13 | # it under the terms of the GNU General Public License as published by |
| 14 | # the Free Software Foundation, either version 2 of the License, or |
| 15 | # (at your option) any later version. |
| 16 | # |
| 17 | # This program is distributed in the hope that it will be useful, |
| 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 20 | # GNU General Public License for more details. |
| 21 | # |
| 22 | # You should have received a copy of the GNU General Public License |
| 23 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 24 | |
| 25 | |
| 26 | class HexAdapter(Adapter): |
| 27 | """convert a bytes() type to a string of hex nibbles.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 28 | |
Harald Welte | e0f9ef1 | 2021-04-10 17:22:35 +0200 | [diff] [blame] | 29 | def _decode(self, obj, context, path): |
| 30 | return b2h(obj) |
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 _encode(self, obj, context, path): |
| 33 | return h2b(obj) |
| 34 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 35 | |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 36 | class BcdAdapter(Adapter): |
| 37 | """convert a bytes() type to a string of BCD nibbles.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 38 | |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 39 | def _decode(self, obj, context, path): |
| 40 | return swap_nibbles(b2h(obj)) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 41 | |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 42 | def _encode(self, obj, context, path): |
| 43 | return h2b(swap_nibbles(obj)) |
| 44 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 45 | |
Robert Falkenberg | b07a3e9 | 2021-05-07 15:23:20 +0200 | [diff] [blame] | 46 | class Rpad(Adapter): |
| 47 | """ |
| 48 | Encoder appends padding bytes (b'\\xff') up to target size. |
| 49 | Decoder removes trailing padding bytes. |
| 50 | |
| 51 | Parameters: |
| 52 | subcon: Subconstruct as defined by construct library |
| 53 | pattern: set padding pattern (default: b'\\xff') |
| 54 | """ |
| 55 | |
| 56 | def __init__(self, subcon, pattern=b'\xff'): |
| 57 | super().__init__(subcon) |
| 58 | self.pattern = pattern |
| 59 | |
| 60 | def _decode(self, obj, context, path): |
| 61 | return obj.rstrip(self.pattern) |
| 62 | |
| 63 | def _encode(self, obj, context, path): |
| 64 | if len(obj) > self.sizeof(): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 65 | raise SizeofError("Input ({}) exceeds target size ({})".format( |
| 66 | len(obj), self.sizeof())) |
Robert Falkenberg | b07a3e9 | 2021-05-07 15:23:20 +0200 | [diff] [blame] | 67 | return obj + self.pattern * (self.sizeof() - len(obj)) |
| 68 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 69 | |
Robert Falkenberg | b07a3e9 | 2021-05-07 15:23:20 +0200 | [diff] [blame] | 70 | class GsmStringAdapter(Adapter): |
| 71 | """Convert GSM 03.38 encoded bytes to a string.""" |
| 72 | |
| 73 | def __init__(self, subcon, codec='gsm03.38', err='strict'): |
| 74 | super().__init__(subcon) |
| 75 | self.codec = codec |
| 76 | self.err = err |
| 77 | |
| 78 | def _decode(self, obj, context, path): |
| 79 | return obj.decode(self.codec) |
| 80 | |
| 81 | def _encode(self, obj, context, path): |
| 82 | return obj.encode(self.codec, self.err) |
| 83 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 84 | |
Harald Welte | e0f9ef1 | 2021-04-10 17:22:35 +0200 | [diff] [blame] | 85 | def filter_dict(d, exclude_prefix='_'): |
| 86 | """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] | 87 | if not isinstance(d, dict): |
| 88 | return d |
Harald Welte | e0f9ef1 | 2021-04-10 17:22:35 +0200 | [diff] [blame] | 89 | res = {} |
| 90 | for (key, value) in d.items(): |
| 91 | if key.startswith(exclude_prefix): |
| 92 | continue |
| 93 | if type(value) is dict: |
| 94 | res[key] = filter_dict(value) |
| 95 | else: |
| 96 | res[key] = value |
| 97 | return res |
| 98 | |
Harald Welte | 07c7b1f | 2021-05-28 22:01:29 +0200 | [diff] [blame] | 99 | |
| 100 | def normalize_construct(c): |
| 101 | """Convert a construct specific type to a related base type, mostly useful |
| 102 | so we can serialize it.""" |
| 103 | # we need to include the filter_dict as we otherwise get elements like this |
| 104 | # in the dict: '_io': <_io.BytesIO object at 0x7fdb64e05860> which we cannot json-serialize |
| 105 | c = filter_dict(c) |
| 106 | if isinstance(c, Container) or isinstance(c, dict): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 107 | r = {k: normalize_construct(v) for (k, v) in c.items()} |
Harald Welte | 07c7b1f | 2021-05-28 22:01:29 +0200 | [diff] [blame] | 108 | elif isinstance(c, ListContainer): |
| 109 | r = [normalize_construct(x) for x in c] |
| 110 | elif isinstance(c, list): |
| 111 | r = [normalize_construct(x) for x in c] |
| 112 | elif isinstance(c, EnumIntegerString): |
| 113 | r = str(c) |
| 114 | else: |
| 115 | r = c |
| 116 | return r |
| 117 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 118 | |
| 119 | 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] | 120 | """Helper function to wrap around normalize_construct() and filter_dict().""" |
| 121 | if not length: |
| 122 | length = len(raw_bin_data) |
| 123 | parsed = c.parse(raw_bin_data, total_len=length) |
| 124 | return normalize_construct(parsed) |
| 125 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 126 | |
Harald Welte | e0f9ef1 | 2021-04-10 17:22:35 +0200 | [diff] [blame] | 127 | # here we collect some shared / common definitions of data types |
| 128 | LV = Prefixed(Int8ub, HexAdapter(GreedyBytes)) |
Robert Falkenberg | 9d16fbc | 2021-04-12 11:43:22 +0200 | [diff] [blame] | 129 | |
| 130 | # Default value for Reserved for Future Use (RFU) bits/bytes |
| 131 | # See TS 31.101 Sec. "3.4 Coding Conventions" |
| 132 | __RFU_VALUE = 0 |
| 133 | |
| 134 | # Field that packs Reserved for Future Use (RFU) bit |
| 135 | FlagRFU = Default(Flag, __RFU_VALUE) |
| 136 | |
| 137 | # Field that packs Reserved for Future Use (RFU) byte |
| 138 | ByteRFU = Default(Byte, __RFU_VALUE) |
| 139 | |
| 140 | # Field that packs all remaining Reserved for Future Use (RFU) bytes |
| 141 | GreedyBytesRFU = Default(GreedyBytes, b'') |
| 142 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 143 | |
Robert Falkenberg | 9d16fbc | 2021-04-12 11:43:22 +0200 | [diff] [blame] | 144 | def BitsRFU(n=1): |
| 145 | ''' |
| 146 | Field that packs Reserved for Future Use (RFU) bit(s) |
| 147 | as defined in TS 31.101 Sec. "3.4 Coding Conventions" |
| 148 | |
| 149 | Use this for (currently) unused/reserved bits whose contents |
| 150 | should be initialized automatically but should not be cleared |
| 151 | in the future or when restoring read data (unlike padding). |
| 152 | |
| 153 | Parameters: |
| 154 | n (Integer): Number of bits (default: 1) |
| 155 | ''' |
| 156 | return Default(BitsInteger(n), __RFU_VALUE) |
| 157 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 158 | |
Robert Falkenberg | 9d16fbc | 2021-04-12 11:43:22 +0200 | [diff] [blame] | 159 | def BytesRFU(n=1): |
| 160 | ''' |
| 161 | Field that packs Reserved for Future Use (RFU) byte(s) |
| 162 | as defined in TS 31.101 Sec. "3.4 Coding Conventions" |
| 163 | |
| 164 | Use this for (currently) unused/reserved bytes whose contents |
| 165 | should be initialized automatically but should not be cleared |
| 166 | in the future or when restoring read data (unlike padding). |
| 167 | |
| 168 | Parameters: |
| 169 | n (Integer): Number of bytes (default: 1) |
| 170 | ''' |
| 171 | return Default(Bytes(n), __RFU_VALUE) |
Robert Falkenberg | b07a3e9 | 2021-05-07 15:23:20 +0200 | [diff] [blame] | 172 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 173 | |
Robert Falkenberg | b07a3e9 | 2021-05-07 15:23:20 +0200 | [diff] [blame] | 174 | def GsmString(n): |
| 175 | ''' |
| 176 | GSM 03.38 encoded byte string of fixed length n. |
| 177 | Encoder appends padding bytes (b'\\xff') to maintain |
| 178 | length. Decoder removes those trailing bytes. |
| 179 | |
| 180 | Exceptions are raised for invalid characters |
| 181 | and length excess. |
| 182 | |
| 183 | Parameters: |
| 184 | n (Integer): Fixed length of the encoded byte string |
| 185 | ''' |
| 186 | return GsmStringAdapter(Rpad(Bytes(n), pattern=b'\xff'), codec='gsm03.38') |