pyosmocom 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
osmocom/__init__.py ADDED
File without changes
osmocom/construct.py ADDED
@@ -0,0 +1,630 @@
1
+ """Utility code related to the integration of the 'construct' declarative parser."""
2
+
3
+ import typing
4
+ import codecs
5
+ import ipaddress
6
+
7
+ import gsm0338
8
+
9
+
10
+ # pylint: disable=import-error,no-name-in-module
11
+ from construct.lib.containers import Container, ListContainer
12
+ from construct.core import EnumIntegerString
13
+ from construct import Adapter, Prefixed, Int8ub, GreedyBytes, Default, Flag, Byte, Construct, Enum
14
+ from construct import BitsInteger, BitStruct, Bytes, StreamError, stream_read_entire, stream_write
15
+ from construct import SizeofError, IntegerError, swapbytes
16
+ from construct.core import evaluate
17
+ from construct.lib import integertypes
18
+
19
+ from osmocom.utils import b2h, h2b, swap_nibbles
20
+
21
+ # (C) 2021-2022 by Harald Welte <laforge@osmocom.org>
22
+ #
23
+ # This program is free software: you can redistribute it and/or modify
24
+ # it under the terms of the GNU General Public License as published by
25
+ # the Free Software Foundation, either version 2 of the License, or
26
+ # (at your option) any later version.
27
+ #
28
+ # This program is distributed in the hope that it will be useful,
29
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
30
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
31
+ # GNU General Public License for more details.
32
+ #
33
+ # You should have received a copy of the GNU General Public License
34
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
35
+
36
+
37
+ class HexAdapter(Adapter):
38
+ """convert a bytes() type to a string of hex nibbles."""
39
+
40
+ def _decode(self, obj, context, path):
41
+ return b2h(obj)
42
+
43
+ def _encode(self, obj, context, path):
44
+ return h2b(obj)
45
+
46
+ class Utf8Adapter(Adapter):
47
+ """convert a bytes() type that contains utf8 encoded text to human readable text."""
48
+
49
+ def _decode(self, obj, context, path):
50
+ # In case the string contains only 0xff bytes we interpret it as an empty string
51
+ if obj == b'\xff' * len(obj):
52
+ return ""
53
+ return codecs.decode(obj, "utf-8")
54
+
55
+ def _encode(self, obj, context, path):
56
+ return codecs.encode(obj, "utf-8")
57
+
58
+ class GsmOrUcs2Adapter(Adapter):
59
+ """Try to encode into a GSM 03.38 string; if that fails, fall back to UCS-2 as described
60
+ in TS 102 221 Annex A."""
61
+ def _decode(self, obj, context, path):
62
+ # In case the string contains only 0xff bytes we interpret it as an empty string
63
+ if obj == b'\xff' * len(obj):
64
+ return ""
65
+ # one of the magic bytes of TS 102 221 Annex A
66
+ if obj[0] in [0x80, 0x81, 0x82]:
67
+ ad = Ucs2Adapter(GreedyBytes)
68
+ else:
69
+ ad = GsmString(GreedyBytes)
70
+ return ad._decode(obj, context, path)
71
+
72
+ def _encode(self, obj, context, path):
73
+ # first try GSM 03.38; then fall back to TS 102 221 Annex A UCS-2
74
+ try:
75
+ ad = GsmString(GreedyBytes)
76
+ return ad._encode(obj, context, path)
77
+ except:
78
+ ad = Ucs2Adapter(GreedyBytes)
79
+ return ad._encode(obj, context, path)
80
+
81
+ class Ucs2Adapter(Adapter):
82
+ """convert a bytes() type that contains UCS2 encoded characters encoded as defined in TS 102 221
83
+ Annex A to normal python string representation (and back)."""
84
+ def _decode(self, obj, context, path):
85
+ # In case the string contains only 0xff bytes we interpret it as an empty string
86
+ if obj == b'\xff' * len(obj):
87
+ return ""
88
+ if obj[0] == 0x80:
89
+ # TS 102 221 Annex A Variant 1
90
+ return codecs.decode(obj[1:], 'utf_16_be')
91
+ elif obj[0] == 0x81:
92
+ # TS 102 221 Annex A Variant 2
93
+ out = ""
94
+ # second byte contains a value indicating the number of characters
95
+ num_of_chars = obj[1]
96
+ # the third byte contains an 8 bit number which defines bits 15 to 8 of a 16 bit base
97
+ # pointer, where bit 16 is set to zero, and bits 7 to 1 are also set to zero. These
98
+ # sixteen bits constitute a base pointer to a "half-page" in the UCS2 code space
99
+ base_ptr = obj[2] << 7
100
+ for ch in obj[3:3+num_of_chars]:
101
+ # if bit 8 of the byte is set to zero, the remaining 7 bits of the byte contain a
102
+ # GSM Default Alphabet character, whereas if bit 8 of the byte is set to one, then
103
+ # the remaining seven bits are an offset value added to the 16 bit base pointer
104
+ # defined earlier, and the resultant 16 bit value is a UCS2 code point
105
+ if ch & 0x80:
106
+ codepoint = (ch & 0x7f) + base_ptr
107
+ out += codecs.decode(codepoint.to_bytes(2, byteorder='big'), 'utf_16_be')
108
+ else:
109
+ out += codecs.decode(bytes([ch]), 'gsm03.38')
110
+ return out
111
+ elif obj[0] == 0x82:
112
+ # TS 102 221 Annex A Variant 3
113
+ out = ""
114
+ # second byte contains a value indicating the number of characters
115
+ num_of_chars = obj[1]
116
+ # third and fourth bytes contain a 16 bit number which defines the complete 16 bit base
117
+ # pointer to a half-page in the UCS2 code space, for use with some or all of the
118
+ # remaining bytes in the string
119
+ base_ptr = obj[2] << 8 | obj[3]
120
+ for ch in obj[4:4+num_of_chars]:
121
+ # if bit 8 of the byte is set to zero, the remaining 7 bits of the byte contain a
122
+ # GSM Default Alphabet character, whereas if bit 8 of the byte is set to one, the
123
+ # remaining seven bits are an offset value added to the base pointer defined in
124
+ # bytes three and four, and the resultant 16 bit value is a UCS2 code point, else: #
125
+ # GSM default alphabet
126
+ if ch & 0x80:
127
+ codepoint = (ch & 0x7f) + base_ptr
128
+ out += codecs.decode(codepoint.to_bytes(2, byteorder='big'), 'utf_16_be')
129
+ else:
130
+ out += codecs.decode(bytes([ch]), 'gsm03.38')
131
+ return out
132
+ else:
133
+ raise ValueError('First byte of TS 102 221 UCS-2 must be 0x80, 0x81 or 0x82')
134
+
135
+ def _encode(self, obj, context, path):
136
+ def encodable_in_gsm338(instr: str) -> bool:
137
+ """Determine if given input string is encode-ale in gsm03.38."""
138
+ try:
139
+ # TODO: figure out if/how we can constrain to default alphabet. The gsm0338
140
+ # library seems to include the spanish lock/shift table
141
+ codecs.encode(instr, 'gsm03.38')
142
+ except ValueError:
143
+ return False
144
+ return True
145
+
146
+ def codepoints_not_in_gsm338(instr: str) -> typing.List[int]:
147
+ """Return an integer list of UCS2 codepoints for all characters of 'inster'
148
+ which are not representable in the GSM 03.38 default alphabet."""
149
+ codepoint_list = []
150
+ for c in instr:
151
+ if encodable_in_gsm338(c):
152
+ continue
153
+ c_codepoint = int.from_bytes(codecs.encode(c, 'utf_16_be'), byteorder='big')
154
+ codepoint_list.append(c_codepoint)
155
+ return codepoint_list
156
+
157
+ def diff_between_min_and_max_of_list(inlst: typing.List) -> int:
158
+ return max(inlst) - min(inlst)
159
+
160
+ def encodable_in_variant2(instr: str) -> bool:
161
+ codepoint_prefix = None
162
+ for c in instr:
163
+ if encodable_in_gsm338(c):
164
+ continue
165
+ c_codepoint = int.from_bytes(codecs.encode(c, 'utf_16_be'), byteorder='big')
166
+ if c_codepoint >= 0x8000:
167
+ return False
168
+ c_prefix = c_codepoint >> 7
169
+ if codepoint_prefix is None:
170
+ codepoint_prefix = c_prefix
171
+ else:
172
+ if c_prefix != codepoint_prefix:
173
+ return False
174
+ return True
175
+
176
+ def encodable_in_variant3(instr: str) -> bool:
177
+ codepoint_list = codepoints_not_in_gsm338(instr)
178
+ # compute delta between max and min; check if it's encodable in 7 bits
179
+ if diff_between_min_and_max_of_list(codepoint_list) >= 0x80:
180
+ return False
181
+ return True
182
+
183
+ def _encode_variant1(instr: str) -> bytes:
184
+ """Encode according to TS 102 221 Annex A Variant 1"""
185
+ return b'\x80' + codecs.encode(instr, 'utf_16_be')
186
+
187
+ def _encode_variant2(instr: str) -> bytes:
188
+ """Encode according to TS 102 221 Annex A Variant 2"""
189
+ codepoint_prefix = None
190
+ # second byte contains a value indicating the number of characters
191
+ hdr = b'\x81' + len(instr).to_bytes(1, byteorder='big')
192
+ chars = b''
193
+ for c in instr:
194
+ try:
195
+ enc = codecs.encode(c, 'gsm03.38')
196
+ except ValueError:
197
+ c_codepoint = int.from_bytes(codecs.encode(c, 'utf_16_be'), byteorder='big')
198
+ c_prefix = c_codepoint >> 7
199
+ if codepoint_prefix is None:
200
+ codepoint_prefix = c_prefix
201
+ assert codepoint_prefix == c_prefix
202
+ enc = (0x80 + (c_codepoint & 0x7f)).to_bytes(1, byteorder='big')
203
+ chars += enc
204
+ if codepoint_prefix is None:
205
+ codepoint_prefix = 0
206
+ return hdr + codepoint_prefix.to_bytes(1, byteorder='big') + chars
207
+
208
+ def _encode_variant3(instr: str) -> bytes:
209
+ """Encode according to TS 102 221 Annex A Variant 3"""
210
+ # second byte contains a value indicating the number of characters
211
+ hdr = b'\x82' + len(instr).to_bytes(1, byteorder='big')
212
+ chars = b''
213
+ codepoint_list = codepoints_not_in_gsm338(instr)
214
+ codepoint_base = min(codepoint_list)
215
+ for c in instr:
216
+ try:
217
+ # if bit 8 of the byte is set to zero, the remaining 7 bits of the byte contain a GSM
218
+ # Default # Alphabet character
219
+ enc = codecs.encode(c, 'gsm03.38')
220
+ except ValueError:
221
+ # if bit 8 of the byte is set to one, the remaining seven bits are an offset
222
+ # value added to the base pointer defined in bytes three and four, and the
223
+ # resultant 16 bit value is a UCS2 code point
224
+ c_codepoint = int.from_bytes(codecs.encode(c, 'utf_16_be'), byteorder='big')
225
+ c_codepoint_delta = c_codepoint - codepoint_base
226
+ assert c_codepoint_delta < 0x80
227
+ enc = (0x80 + c_codepoint_delta).to_bytes(1, byteorder='big')
228
+ chars += enc
229
+ # third and fourth bytes contain a 16 bit number which defines the complete 16 bit base
230
+ # pointer to a half-page in the UCS2 code space
231
+ return hdr + codepoint_base.to_bytes(2, byteorder='big') + chars
232
+
233
+ if encodable_in_variant2(obj):
234
+ return _encode_variant2(obj)
235
+ elif encodable_in_variant3(obj):
236
+ return _encode_variant3(obj)
237
+ else:
238
+ return _encode_variant1(obj)
239
+
240
+ class BcdAdapter(Adapter):
241
+ """convert a bytes() type to a string of BCD nibbles."""
242
+
243
+ def _decode(self, obj, context, path):
244
+ return swap_nibbles(b2h(obj))
245
+
246
+ def _encode(self, obj, context, path):
247
+ return h2b(swap_nibbles(obj))
248
+
249
+ class PaddedBcdAdapter(BcdAdapter):
250
+ """Representatin of a BCD string of potentially odd number of BCD digits,
251
+ which then need to be padded at the end with an 'f' nibble."""
252
+ def _decode(self, obj, context, path):
253
+ r = super()._decode(obj, context, path)
254
+ if r[-1] == 'f':
255
+ return r[:-1]
256
+ else:
257
+ return r
258
+
259
+ def _encode(self, obj, context, path):
260
+ if len(obj) & 0x01:
261
+ obj += 'f'
262
+ return super()._encode(obj, context, path)
263
+
264
+ class PlmnAdapter(BcdAdapter):
265
+ """convert a bytes(3) type to BCD string like 262-02 or 262-002."""
266
+ def _decode(self, obj, context, path):
267
+ bcd = super()._decode(obj, context, path)
268
+ if bcd[3] == 'f':
269
+ return '-'.join([bcd[:3], bcd[4:]])
270
+ else:
271
+ return '-'.join([bcd[:3], bcd[3:]])
272
+
273
+ def _encode(self, obj, context, path):
274
+ l = obj.split('-')
275
+ if len(l[1]) == 2:
276
+ bcd = l[0] + 'f' + l[1]
277
+ else:
278
+ bcd = l[0] + l[1]
279
+ return super()._encode(bcd, context, path)
280
+
281
+ class InvertAdapter(Adapter):
282
+ """inverse logic (false->true, true->false)."""
283
+ @staticmethod
284
+ def _invert_bool_in_obj(obj):
285
+ for k,v in obj.items():
286
+ # skip all private entries
287
+ if k.startswith('_'):
288
+ continue
289
+ if v is False:
290
+ obj[k] = True
291
+ elif v is True:
292
+ obj[k] = False
293
+ return obj
294
+
295
+ def _decode(self, obj, context, path):
296
+ return self._invert_bool_in_obj(obj)
297
+
298
+ def _encode(self, obj, context, path):
299
+ return self._invert_bool_in_obj(obj)
300
+
301
+ class DnsAdapter(Adapter):
302
+ """Convert between DNS label format (length-prefixed labels) and string format."""
303
+ def _decode(self, obj, context, path):
304
+ labels = []
305
+ remainder = bytes(obj)
306
+ while True:
307
+ label_len = remainder[0]
308
+ label = remainder[1:1+label_len].decode('ascii')
309
+ labels.append(label)
310
+ remainder = remainder[1+label_len:]
311
+ if not len(remainder):
312
+ break
313
+ return '.'.join(labels)
314
+
315
+ def _encode(self, obj, context, path):
316
+ labels = obj.split('.')
317
+ out = b''
318
+ for label in labels:
319
+ out += bytes([len(label)])
320
+ out += label.encode('ascii')
321
+ return out
322
+
323
+
324
+ class Rpad(Adapter):
325
+ """
326
+ Encoder appends padding bytes (b'\\xff') or characters up to target size.
327
+ Decoder removes trailing padding bytes/characters.
328
+
329
+ Parameters:
330
+ subcon: Subconstruct as defined by construct library
331
+ pattern: set padding pattern (default: b'\\xff')
332
+ num_per_byte: number of 'elements' per byte. E.g. for hex nibbles: 2
333
+ """
334
+
335
+ def __init__(self, subcon, pattern=b'\xff', num_per_byte=1):
336
+ super().__init__(subcon)
337
+ self.pattern = pattern
338
+ self.num_per_byte = num_per_byte
339
+
340
+ def _decode(self, obj, context, path):
341
+ return obj.rstrip(self.pattern)
342
+
343
+ def _encode(self, obj, context, path):
344
+ target_size = self.sizeof() * self.num_per_byte
345
+ if len(obj) > target_size:
346
+ raise SizeofError("Input ({}) exceeds target size ({})".format(
347
+ len(obj), target_size))
348
+ return obj + self.pattern * (target_size - len(obj))
349
+
350
+ class MultiplyAdapter(Adapter):
351
+ """
352
+ Decoder multiplies by multiplicator
353
+ Encoder divides by multiplicator
354
+
355
+ Parameters:
356
+ subcon: Subconstruct as defined by construct library
357
+ multiplier: Multiplier to apply to raw encoded value
358
+ """
359
+
360
+ def __init__(self, subcon, multiplicator):
361
+ super().__init__(subcon)
362
+ self.multiplicator = multiplicator
363
+
364
+ def _decode(self, obj, context, path):
365
+ return obj * 8
366
+
367
+ def _encode(self, obj, context, path):
368
+ return obj // 8
369
+
370
+
371
+ class GsmStringAdapter(Adapter):
372
+ """Convert GSM 03.38 encoded bytes to a string."""
373
+
374
+ def __init__(self, subcon, codec='gsm03.38', err='strict'):
375
+ super().__init__(subcon)
376
+ self.codec = codec
377
+ self.err = err
378
+
379
+ def _decode(self, obj, context, path):
380
+ return obj.decode(self.codec)
381
+
382
+ def _encode(self, obj, context, path):
383
+ return obj.encode(self.codec, self.err)
384
+
385
+ class Ipv4Adapter(Adapter):
386
+ """
387
+ Encoder converts from 4 bytes to string representation (A.B.C.D).
388
+ Decoder converts from string representation (A.B.C.D) to four bytes.
389
+ """
390
+ def _decode(self, obj, context, path):
391
+ ia = ipaddress.IPv4Address(obj)
392
+ return ia.compressed
393
+
394
+ def _encode(self, obj, context, path):
395
+ ia = ipaddress.IPv4Address(obj)
396
+ return ia.packed
397
+
398
+ class Ipv6Adapter(Adapter):
399
+ """
400
+ Encoder converts from 16 bytes to string representation.
401
+ Decoder converts from string representation to 16 bytes.
402
+ """
403
+ def _decode(self, obj, context, path):
404
+ ia = ipaddress.IPv6Address(obj)
405
+ return ia.compressed
406
+
407
+ def _encode(self, obj, context, path):
408
+ ia = ipaddress.IPv6Address(obj)
409
+ return ia.packed
410
+
411
+ class StripTrailerAdapter(Adapter):
412
+ """
413
+ Encoder removes all trailing bytes matching the default_value
414
+ Decoder pads input data up to total_length with default_value
415
+
416
+ This is used in constellations like "FlagsEnum(StripTrailerAdapter(GreedyBytes, 3), ..."
417
+ where you have a bit-mask that may have 1, 2 or 3 bytes, depending on whether or not any
418
+ of the LSBs are actually set.
419
+ """
420
+ def __init__(self, subcon, total_length:int, default_value=b'\x00', min_len=1):
421
+ super().__init__(subcon)
422
+ assert len(default_value) == 1
423
+ self.total_length = total_length
424
+ self.default_value = default_value
425
+ self.min_len = min_len
426
+
427
+ def _decode(self, obj, context, path):
428
+ assert isinstance(obj, bytes)
429
+ # pad with suppressed/missing bytes
430
+ if len(obj) < self.total_length:
431
+ obj += self.default_value * (self.total_length - len(obj))
432
+ return int.from_bytes(obj, 'big')
433
+
434
+ def _encode(self, obj, context, path):
435
+ assert isinstance(obj, int)
436
+ obj = obj.to_bytes(self.total_length, 'big')
437
+ # remove trailing bytes if they are zero
438
+ while len(obj) > self.min_len and obj[-1] == self.default_value[0]:
439
+ obj = obj[:-1]
440
+ return obj
441
+
442
+
443
+ def filter_dict(d, exclude_prefix='_'):
444
+ """filter the input dict to ensure no keys starting with 'exclude_prefix' remain."""
445
+ if not isinstance(d, dict):
446
+ return d
447
+ res = {}
448
+ for (key, value) in d.items():
449
+ if key.startswith(exclude_prefix):
450
+ continue
451
+ if isinstance(value, dict):
452
+ res[key] = filter_dict(value)
453
+ else:
454
+ res[key] = value
455
+ return res
456
+
457
+
458
+ def normalize_construct(c, exclude_prefix: str = '_'):
459
+ """Convert a construct specific type to a related base type, mostly useful
460
+ so we can serialize it."""
461
+ # we need to include the filter_dict as we otherwise get elements like this
462
+ # in the dict: '_io': <_io.BytesIO object at 0x7fdb64e05860> which we cannot json-serialize
463
+ c = filter_dict(c, exclude_prefix)
464
+ if isinstance(c, (Container, dict)):
465
+ r = {k: normalize_construct(v) for (k, v) in c.items()}
466
+ elif isinstance(c, ListContainer):
467
+ r = [normalize_construct(x) for x in c]
468
+ elif isinstance(c, list):
469
+ r = [normalize_construct(x) for x in c]
470
+ elif isinstance(c, EnumIntegerString):
471
+ r = str(c)
472
+ else:
473
+ r = c
474
+ return r
475
+
476
+
477
+ def parse_construct(c, raw_bin_data: bytes, length: typing.Optional[int] = None, exclude_prefix: str = '_', context: dict = {}):
478
+ """Helper function to wrap around normalize_construct() and filter_dict()."""
479
+ if not length:
480
+ length = len(raw_bin_data)
481
+ try:
482
+ parsed = c.parse(raw_bin_data, total_len=length, **context)
483
+ except StreamError as e:
484
+ # if the input is all-ff, this means the content is undefined. Let's avoid passing StreamError
485
+ # exceptions in those situations (which might occur if a length field 0xff is 255 but then there's
486
+ # actually less bytes in the remainder of the file.
487
+ if all(v == 0xff for v in raw_bin_data):
488
+ return None
489
+ else:
490
+ raise e
491
+ return normalize_construct(parsed, exclude_prefix)
492
+
493
+ def build_construct(c, decoded_data, context: dict = {}):
494
+ """Helper function to handle total_len."""
495
+ return c.build(decoded_data, total_len=None, **context)
496
+
497
+ # here we collect some shared / common definitions of data types
498
+ LV = Prefixed(Int8ub, HexAdapter(GreedyBytes))
499
+
500
+ # Default value for Reserved for Future Use (RFU) bits/bytes
501
+ # See TS 31.101 Sec. "3.4 Coding Conventions"
502
+ __RFU_VALUE = 0
503
+
504
+ # Field that packs Reserved for Future Use (RFU) bit
505
+ FlagRFU = Default(Flag, __RFU_VALUE)
506
+
507
+ # Field that packs Reserved for Future Use (RFU) byte
508
+ ByteRFU = Default(Byte, __RFU_VALUE)
509
+
510
+ # Field that packs all remaining Reserved for Future Use (RFU) bytes
511
+ GreedyBytesRFU = Default(GreedyBytes, b'')
512
+
513
+
514
+ def BitsRFU(n=1):
515
+ '''
516
+ Field that packs Reserved for Future Use (RFU) bit(s)
517
+ as defined in TS 31.101 Sec. "3.4 Coding Conventions"
518
+
519
+ Use this for (currently) unused/reserved bits whose contents
520
+ should be initialized automatically but should not be cleared
521
+ in the future or when restoring read data (unlike padding).
522
+
523
+ Parameters:
524
+ n (Integer): Number of bits (default: 1)
525
+ '''
526
+ return Default(BitsInteger(n), __RFU_VALUE)
527
+
528
+
529
+ def BytesRFU(n=1):
530
+ '''
531
+ Field that packs Reserved for Future Use (RFU) byte(s)
532
+ as defined in TS 31.101 Sec. "3.4 Coding Conventions"
533
+
534
+ Use this for (currently) unused/reserved bytes whose contents
535
+ should be initialized automatically but should not be cleared
536
+ in the future or when restoring read data (unlike padding).
537
+
538
+ Parameters:
539
+ n (Integer): Number of bytes (default: 1)
540
+ '''
541
+ return Default(Bytes(n), __RFU_VALUE)
542
+
543
+
544
+ def GsmString(n):
545
+ '''
546
+ GSM 03.38 encoded byte string of fixed length n.
547
+ Encoder appends padding bytes (b'\\xff') to maintain
548
+ length. Decoder removes those trailing bytes.
549
+
550
+ Exceptions are raised for invalid characters
551
+ and length excess.
552
+
553
+ Parameters:
554
+ n (Integer): Fixed length of the encoded byte string
555
+ '''
556
+ return GsmStringAdapter(Rpad(Bytes(n), pattern=b'\xff'), codec='gsm03.38')
557
+
558
+ def GsmOrUcs2String(n):
559
+ '''
560
+ GSM 03.38 or UCS-2 (TS 102 221 Annex A) encoded byte string of fixed length n.
561
+ Encoder appends padding bytes (b'\\xff') to maintain
562
+ length. Decoder removes those trailing bytes.
563
+
564
+ Exceptions are raised for invalid characters
565
+ and length excess.
566
+
567
+ Parameters:
568
+ n (Integer): Fixed length of the encoded byte string
569
+ '''
570
+ return GsmOrUcs2Adapter(Rpad(Bytes(n), pattern=b'\xff'))
571
+
572
+ class GreedyInteger(Construct):
573
+ """A variable-length integer implementation, think of combining GrredyBytes with BytesInteger."""
574
+ def __init__(self, signed=False, swapped=False, minlen=0):
575
+ super().__init__()
576
+ self.signed = signed
577
+ self.swapped = swapped
578
+ self.minlen = minlen
579
+
580
+ def _parse(self, stream, context, path):
581
+ data = stream_read_entire(stream, path)
582
+ if evaluate(self.swapped, context):
583
+ data = swapbytes(data)
584
+ try:
585
+ return int.from_bytes(data, byteorder='big', signed=self.signed)
586
+ except ValueError as e:
587
+ raise IntegerError(str(e), path=path)
588
+
589
+ def __bytes_required(self, i, minlen=0):
590
+ if self.signed:
591
+ raise NotImplementedError("FIXME: Implement support for encoding signed integer")
592
+
593
+ # compute how many bytes we need
594
+ nbytes = 1
595
+ while True:
596
+ i = i >> 8
597
+ if i == 0:
598
+ break
599
+ else:
600
+ nbytes = nbytes + 1
601
+
602
+ # round up to the minimum number
603
+ # of bytes we anticipate
604
+ nbytes = max(nbytes, minlen)
605
+
606
+ return nbytes
607
+
608
+ def _build(self, obj, stream, context, path):
609
+ if not isinstance(obj, integertypes):
610
+ raise IntegerError(f"value {obj} is not an integer", path=path)
611
+ length = self.__bytes_required(obj, self.minlen)
612
+ try:
613
+ data = obj.to_bytes(length, byteorder='big', signed=self.signed)
614
+ except ValueError as e:
615
+ raise IntegerError(str(e), path=path) from e
616
+ if evaluate(self.swapped, context):
617
+ data = swapbytes(data)
618
+ stream_write(stream, data, length, path)
619
+ return obj
620
+
621
+ # merged definitions of 24.008 + 23.040
622
+ TypeOfNumber = Enum(BitsInteger(3), unknown=0, international=1, national=2, network_specific=3,
623
+ short_code=4, alphanumeric=5, abbreviated=6, reserved_for_extension=7)
624
+ NumberingPlan = Enum(BitsInteger(4), unknown=0, isdn_e164=1, data_x121=3, telex_f69=4,
625
+ sc_specific_5=5, sc_specific_6=6, national=8, private=9,
626
+ ermes=10, reserved_cts=11, reserved_for_extension=15)
627
+ TonNpi = BitStruct('ext'/Flag, 'type_of_number'/TypeOfNumber, 'numbering_plan_id'/NumberingPlan)
628
+
629
+ # see 'struct osmo_rat_type' in osmocom/gsm/gsm_utils.h
630
+ OsmoRatType = Enum(Int8ub, unknown=0, geran=1, utran=2, eutran=3)
File without changes