globally remove Python 2 compat

This commit is contained in:
p1-bmu 2023-04-06 15:48:00 +02:00
parent 22c6a5daec
commit 87d633859b
33 changed files with 150 additions and 491 deletions

View File

@ -120,18 +120,12 @@ def get_spec_files(spec_dir):
spec_texts, spec_fn = [], []
for fn in load:
try:
if python_version < 3:
fd = open('%s%s' % (spec_dir, fn), 'r')
else:
fd = open('%s%s' % (spec_dir, fn), 'r', encoding='utf-8')
fd = open('%s%s' % (spec_dir, fn), 'r', encoding='utf-8')
except Exception as err:
raise(ASN1Err(
'[proc] unable to open spec file {0}, {1}'.format(fn, err)))
try:
if python_version < 3:
spec_texts.append( fd.read().decode('utf-8') )
else:
spec_texts.append( fd.read() )
spec_texts.append( fd.read() )
except Exception as err:
fd.close()
raise(ASN1Err(

View File

@ -27,8 +27,6 @@
# *--------------------------------------------------------
#*/
from .utils import python_version
#------------------------------------------------------------------------------#
# ordered dictionnary
#------------------------------------------------------------------------------#
@ -108,27 +106,16 @@ class ASN1Dict(object):
for key, val in other.items():
self.__setitem__(key, val)
if python_version <= 2:
def keys(self):
return list(self._index)
def items(self):
return [(k, self._dict[k]) for k in self._index]
def values(self):
return [self._dict[k] for k in self._index]
def keys(self):
return self._index.__iter__()
else:
def keys(self):
return self._index.__iter__()
def items(self):
# TODO: create a true iterator instead of a complete list over which we then iterate
return [(k, self._dict[k]) for k in self._index].__iter__()
def values(self):
# TODO: create a true iterator instead of a complete list over which we then iterate
return [self._dict[k] for k in self._index].__iter__()
def items(self):
# TODO: create a true iterator instead of a complete list over which we then iterate
return [(k, self._dict[k]) for k in self._index].__iter__()
def values(self):
# TODO: create a true iterator instead of a complete list over which we then iterate
return [self._dict[k] for k in self._index].__iter__()
# custom pycrate_asn1 methods
def copy(self):

View File

@ -155,10 +155,7 @@ def value_to_defin(v, Obj=None, Gen=None, ind=None):
return '(%s, %s)' % (vv, vl)
elif Obj.TYPE == TYPE_OCT_STR:
# byte-string
if python_version > 2:
return repr(v)
else:
return 'b%s' % repr(v)
return repr(v)
elif Obj.TYPE == TYPE_OID:
# list of int -> convert to tuple
return repr(tuple(v))

View File

@ -952,10 +952,7 @@ def test():
if fn[-4:] == '.asn':
fp = '%s%s/%s' % (p, S, fn)
print(fp)
if python_version < 3:
mods = tokenize_text(open(fp).read().decode('utf-8'))
else:
mods = tokenize_text(open(fp).read())
mods = tokenize_text(open(fp).read())
for modname, moddict in mods.items():
M[modname] = moddict
return M

View File

@ -32,7 +32,7 @@ import pprint
from keyword import iskeyword
# pycrate_core is used only for basic library-wide functions / variables:
# log(), python_version, integer_types, str_types
# log(), integer_types, str_types
from pycrate_core.utils import *
from .err import ASN1Err
@ -42,7 +42,7 @@ from .err import ASN1Err
def asnlog(msg):
"""
customizable logging function for the whole asn1 part
customizable logging function for the whole asn1c part
"""
log(msg)

View File

@ -786,10 +786,7 @@ Specific attribute:
# base 10: character string encoding
if B0 == 1:
# NR1 encoding, simple whole numbers
if python_version < 3:
m = self._NR1_RE.match( bytes[1:] )
else:
m = self._NR1_RE.match( str(bytes[1:], 'ascii') )
m = self._NR1_RE.match( str(bytes[1:], 'ascii') )
if not m:
raise(ASN1BERDecodeErr('{0}: invalid REAL base 10 NR1 encoding, {1!r}'\
.format(self.fullname(), bytes[1:])))
@ -797,10 +794,7 @@ Specific attribute:
self._val = (mant, 10, 0)
elif B0 == 2:
# NR2 encoding, requires a decimal mark
if python_version < 3:
m = self._NR2_RE.match( bytes[1:] )
else:
m = self._NR2_RE.match( str(bytes[1:], 'ascii') )
m = self._NR2_RE.match( str(bytes[1:], 'ascii') )
if not m:
raise(ASN1BERDecodeErr('{0}: invalid REAL base 10 NR2 encoding, {1!r}'\
.format(self.fullname(), bytes[1:])))
@ -812,10 +806,7 @@ Specific attribute:
self._val = (int(i+d), 10, e)
elif B0 == 3:
# NR3 encoding, requires the exponent notation
if python_version < 3:
m = self._NR3_RE.match( bytes[1:] )
else:
m = self._NR3_RE.match( str(bytes[1:], 'ascii') )
m = self._NR3_RE.match( str(bytes[1:], 'ascii') )
if not m:
raise(ASN1BERDecodeErr('{0}: invalid REAL base 10 NR3 encoding, {1!r}'\
.format(self.fullname(), bytes[1:])))
@ -890,21 +881,12 @@ Specific attribute:
raise(ASN1BEREncodeErr('{0}: invalid REAL base 10 encoding NR1 for decimal value'\
.format(self.fullname())))
i = self._val[0] * (10**self._val[2])
if python_version < 3:
return '\x01' + \
ASN1CodecBER.ENC_REALNR1_SPA * ' ' + \
ASN1CodecBER.ENC_REALNR1_ZER * '0' + \
str(i)
else:
return b'\x01' + \
ASN1CodecBER.ENC_REALNR1_SPA * b' ' + \
ASN1CodecBER.ENC_REALNR1_ZER * b'0' + \
bytes(str(i), 'ascii')
return b'\x01' + \
ASN1CodecBER.ENC_REALNR1_SPA * b' ' + \
ASN1CodecBER.ENC_REALNR1_ZER * b'0' + \
bytes(str(i), 'ascii')
elif ASN1CodecBER.ENC_REALNR == 2:
if python_version < 3:
i = bytes(self._val[0])
else:
i = bytes(str(self._val[0]), 'ascii')
i = bytes(str(self._val[0]), 'ascii')
if self._val[2] >= 0:
# we need to add trailing zero
i += self._val[2] * b'0'
@ -926,20 +908,14 @@ Specific attribute:
ASN1CodecBER.ENC_REALNR2_ZERTRAIL * b'0'
else:
#ASN1CodecBER.ENC_REALNR == 3
if python_version < 3:
i, e = bytes(self._val[0]), self._val[2]
else:
i, e = bytes(str(self._val[0]), 'ascii'), self._val[2]
i, e = bytes(str(self._val[0]), 'ascii'), self._val[2]
# remove trailing zero
while i[-1:] == b'0':
i = i[:-1]
e += 1
if e == 0:
e = b'+0'
elif python_version < 3:
e = bytes(e)
else:
e = bytes(str(e), 'ascii')
e = bytes(str(e), 'ascii')
return b'\x03' + i + b'.E' + e
else:
# base 2, encoding the CER / DER way:
@ -957,16 +933,10 @@ Specific attribute:
LE = int_bytelen(E)
E = int_to_bytes(E, 8*LE)
N = uint_to_bytes(m, 8*uint_bytelen(m))
if python_version < 3:
if LE > 3:
return chr(0x80 + (S<<6) + 3) + uint_to_bytes(LE) + E + N
else:
return chr(0x80 + (S<<6) + LE-1) + E + N
if LE > 3:
return bytes((0x80 + (S<<6) + 3, )) + uint_to_bytes(LE) + E + N
else:
if LE > 3:
return bytes((0x80 + (S<<6) + 3, )) + uint_to_bytes(LE) + E + N
else:
return bytes((0x80 + (S<<6) + LE-1, )) + E + N
return bytes((0x80 + (S<<6) + LE-1, )) + E + N
def _decode_ber_cont_ws(self, char, vbnd):
char._cur, char._len_bit = vbnd[0], vbnd[1]
@ -1805,10 +1775,7 @@ Single value: Python tuple of int
for f in fact[:-1]:
by.append( 0x80 + f )
by.append( fact[-1] )
if python_version > 2:
return bytes(by)
else:
return ''.join(map(chr, by))
return bytes(by)
class REL_OID(_OID):
@ -1856,8 +1823,5 @@ Single value: Python tuple of int
for f in fact[:-1]:
by.append( 0x80 + f )
by.append( fact[-1] )
if python_version > 2:
return bytes(by)
else:
return ''.join(map(chr, by))
return bytes(by)

View File

@ -232,10 +232,7 @@ Single value: Python 2-tuple
if isinstance(self._val[0], str_types):
if self._val[0][:5] == '_unk_':
# HSTRING
if python_version >= 3:
return '\'%s\'H' % hexlify(self._val[1]).decode('ascii').upper()
else:
return '\'%s\'H' % hexlify(self._val[1]).upper()
return '\'%s\'H' % hexlify(self._val[1]).decode('ascii').upper()
else:
ident = self._val[0]
Obj = self._get_val_obj(self._val[0])

View File

@ -281,10 +281,7 @@ Specific constraints attributes:
elif self._ASN_WASC and self._val[1] % 8 == 0:
# eventually add printable repr
try:
if python_version < 3:
s = uint_to_bytes(self._val[0], self._val[1])
else:
s = uint_to_bytes(self._val[0], self._val[1]).decode('ascii')
s = uint_to_bytes(self._val[0], self._val[1]).decode('ascii')
if is_printable(s):
return ret + ' -- %s --' % repr(s)[1:-1]
else:
@ -1313,10 +1310,7 @@ Specific constraints attributes:
def _to_asn1(self):
if isinstance(self._val, bytes_types):
# HSTRING
if python_version >= 3:
ret = '\'%s\'H' % hexlify(self._val).decode('ascii').upper()
else:
ret = '\'%s\'H' % hexlify(self._val).upper()
ret = '\'%s\'H' % hexlify(self._val).decode('ascii').upper()
if self._ASN_WASC:
# eventually add printable repr
try:

View File

@ -27,8 +27,6 @@
# *--------------------------------------------------------
#*/
from .utils import python_version
#------------------------------------------------------------------------------#
# ordered dictionnary
#------------------------------------------------------------------------------#
@ -102,27 +100,16 @@ class ASN1Dict(object):
for key, val in other.items():
self.__setitem__(key, val)
if python_version <= 2:
def keys(self):
return list(self._index)
def items(self):
return [(k, self._dict[k]) for k in self._index]
def values(self):
return [self._dict[k] for k in self._index]
def keys(self):
return self._index.__iter__()
else:
def keys(self):
return self._index.__iter__()
def items(self):
# TODO: create a true iterator instead of a complete list over which we then iterate
return [(k, self._dict[k]) for k in self._index].__iter__()
def values(self):
# TODO: create a true iterator instead of a complete list over which we then iterate
return [self._dict[k] for k in self._index].__iter__()
def items(self):
# TODO: create a true iterator instead of a complete list over which we then iterate
return [(k, self._dict[k]) for k in self._index].__iter__()
def values(self):
# TODO: create a true iterator instead of a complete list over which we then iterate
return [self._dict[k] for k in self._index].__iter__()
# custom pycrate_asn1 methods
def copy(self):

View File

@ -39,7 +39,7 @@ from .err import *
from pycrate_asn1c.utils import clean_text
# pycrate_core is used for basic library-wide functions / variables
# (i.e. log(), python_version, integer_types, bytes_types, str_types)
# (i.e. log(), integer_types, bytes_types, str_types)
# and for encoding / decoding routines
from pycrate_core.utils import *
from pycrate_core.utils import TYPE_BYTES as T_BYTES

View File

@ -35,9 +35,6 @@ __all__ = ['Buf', 'BufAuto', 'NullTermStr',
'IntLE', 'Int8LE', 'Int16LE', 'Int24LE', 'Int32LE', 'Int48LE', 'Int64LE']
import sys
python_version = sys.version_info[0]
from .utils import *
from .charpy import Charpy, CharpyErr
from .elt import Atom, EltErr, REPR_RAW, REPR_HEX, REPR_BIN, REPR_HD, REPR_HUM
@ -345,10 +342,7 @@ class String(Atom):
# e.g. utf8, utf16, utf32...
CODEC = 'utf8'
if python_version <= 2:
TYPES = (unicode, )
else:
TYPES = (str, )
TYPES = (str, )
TYPENAMES = get_typenames(*TYPES)
DEFAULT_VAL = u''
DEFAULT_BL = 0

View File

@ -150,14 +150,8 @@ class Charpy(object):
# bytes buffer, default one
r = self.to_bytes()
if len(r) > self._REPR_MAX:
if python_version < 3:
return 'charpy(b{0}...{1})'.format(
repr(r[0:self._REPR_MAX])[:-1], repr(r[-2:])[1:])
else:
return 'charpy({0}...{1})'.format(
repr(r[0:self._REPR_MAX])[:-1], repr(r[-2:])[2:])
elif python_version < 3:
return 'charpy(b{0})'.format(repr(r))
return 'charpy({0}...{1})'.format(
repr(r[0:self._REPR_MAX])[:-1], repr(r[-2:])[2:])
else:
return 'charpy({0})'.format(repr(r))
elif self._REPR == 'bytelist':
@ -1323,13 +1317,10 @@ class Charpy(object):
# Python built-ins override
#--------------------------------------------------------------------------#
__len__ = len_bit
__repr__ = repr
__len__ = len_bit
__repr__ = repr
__index__ = to_uint
if python_version < 3:
__str__ = to_bytes
else:
__bytes__ = to_bytes
__bytes__ = to_bytes
def __bool__(self):
if self.len_bit() == 0:

View File

@ -72,24 +72,14 @@ REPR_HUM = 4
# for hexdump representation
if python_version < 3:
def hview(buf, lw=16):
hv = []
for o in range(0, len(buf), lw):
l = buf[o:o+lw]
# create the hex fmt string for each iteration
hs = '%.2x ' * len(l) % tuple(map(ord, l))
hv.append( ' ' + hs + ' '*(3*lw-len(hs)) + '| %r' % l )
return hv
else:
def hview(buf, lw=16):
hv = []
for o in range(0, len(buf), lw):
l = buf[o:o+lw]
# create the hex fmt string for each iteration
hs = '%.2x ' * len(l) % tuple(l)
hv.append( ' ' + hs + ' '*(3*lw-len(hs)) + '| %r' % l )
return hv
def hview(buf, lw=16):
hv = []
for o in range(0, len(buf), lw):
l = buf[o:o+lw]
# create the hex fmt string for each iteration
hs = '%.2x ' * len(l) % tuple(l)
hv.append( ' ' + hs + ' '*(3*lw-len(hs)) + '| %r' % l )
return hv
#------------------------------------------------------------------------------#
# Element parent class
@ -750,10 +740,7 @@ class Element(object):
b = self.to_bytes()
return bytes_to_int(b, len(b)<<3)
if python_version < 3:
__str__ = to_bytes
else:
__bytes__ = to_bytes
__bytes__ = to_bytes
#--------------------------------------------------------------------------#
# representation routines
@ -2123,14 +2110,9 @@ class Envelope(Element):
Returns:
None
"""
if python_version < 3:
del self._content[:]
del self._by_id[:]
del self._by_name[:]
else:
self._content.clear()
self._by_id.clear()
self._by_name.clear()
self._content.clear()
self._by_id.clear()
self._by_name.clear()
def __iter__(self):
self._it_saved.append(self._it)
@ -2156,9 +2138,6 @@ class Envelope(Element):
# transparent element, pass it and try the next one
return self.__next__()
if python_version < 3:
next = __next__
def __getitem__(self, key):
if isinstance(key, str_types):
try:
@ -3041,10 +3020,7 @@ class Array(Element):
Returns:
None
"""
if python_version < 3:
del self._val[:]
else:
self._val.clear()
self._val.clear()
def __iter__(self):
self._it_saved.append(self._it)
@ -3065,9 +3041,6 @@ class Array(Element):
clone._env = self
return clone
if python_version < 3:
next = __next__
def __getitem__(self, key):
if isinstance(key, integer_types):
try:
@ -3979,10 +3952,7 @@ class Sequence(Element):
Returns:
None
"""
if python_version < 3:
del self._content[:]
else:
self._content.clear()
self._content.clear()
def __iter__(self):
self._it_saved.append(self._it)
@ -4008,9 +3978,6 @@ class Sequence(Element):
# transparent element, pass it and try the next one
return self.__next__()
if python_version < 3:
next = __next__
def __getitem__(self, key):
if isinstance(key, integer_types):
try:

View File

@ -29,10 +29,7 @@
#
import sys
if sys.version_info[0] < 3:
import __builtin__ as builtins
else:
import builtins
import builtins
from .elt import Element
from .charpy import Charpy

View File

@ -28,12 +28,8 @@
#*/
import sys
from .utils_py3 import *
if sys.version_info[0] < 3:
from .utils_py2 import *
else:
from .utils_py3 import *
#
# configure max recursion
#sys.setrecursionlimit(200)

View File

@ -942,22 +942,9 @@ class _DPI(object):
"""return the port TCP / UDP number
"""
return unpack('!H', pay[2:4])[0]
@staticmethod
def __get_dn_req_py2(req):
"""return the DNS name requested
"""
# remove fixed DNS header and Type / Class
s = req[12:-4]
n = []
while len(s) > 1:
l = ord(s[0])
n.append( s[1:1+l] )
s = s[1+l:]
return b'.'.join(n)
@staticmethod
def __get_dn_req_py3(req):
def __get_dn_req(req):
"""return the DNS name requested
"""
# remove fixed DNS header and Type / Class
@ -968,31 +955,12 @@ class _DPI(object):
n.append( s[1:1+l] )
s = s[1+l:]
return b'.'.join(n)
if python_version < 3:
get_dn_req = __get_dn_req_py2
else:
get_dn_req = __get_dn_req_py3
class DPIv4(_DPI):
@staticmethod
def __get_ip_info_py2(ipbuf):
"""return a 3-tuple: ipdst (asc), protocol (uint), payload (bytes)
"""
# returns a 3-tuple: dst IP, protocol, payload buffer
# get IP header length
l = (ord(ipbuf[0]) & 0x0F) * 4
# get dst IP
dst = inet_ntoa(ipbuf[16:20])
# get protocol
prot = ord(ipbuf[9])
#
return (dst, prot, ipbuf[l:])
@staticmethod
def __get_ip_info_py3(ipbuf):
def __get_ip_info(ipbuf):
"""return a 3-tuple: ipdst (asc), protocol (uint), payload (bytes)
"""
# returns a 3-tuple: dst IP, protocol, payload buffer
@ -1004,32 +972,12 @@ class DPIv4(_DPI):
prot = ipbuf[9]
#
return (dst, prot, ipbuf[l:])
if python_version < 3:
get_ip_info = __get_ip_info_py2
else:
get_ip_info = __get_ip_info_py3
class DPIv6(_DPI):
@staticmethod
def __get_ip_info_py2(ipbuf):
"""return a 3-tuple: ipdst (asc), protocol (uint), payload (bytes)
"""
# returns a 3-tuple: dst IP, protocol, payload buffer
# get payload length
pl = unpack('>H', ipbuf[4:6])[0]
# get dst IP
dst = inet_ntop(AF_INET6, ipbuf[24:40])
# get protocol
# TODO: unstack IPv6 opts
prot = ord(ipbuf[6])
#
return (dst, prot, ipbuf[-pl:])
@staticmethod
def __get_ip_info_py3(ipbuf):
def __get_ip_info(ipbuf):
"""return a 3-tuple: ipdst (asc), protocol (uint), payload (bytes)
"""
# returns a 3-tuple: dst IP, protocol, payload buffer
@ -1042,11 +990,6 @@ class DPIv6(_DPI):
prot = ipbuf[6]
#
return (dst, prot, ipbuf[-pl:])
if python_version < 3:
get_ip_info = __get_ip_info_py2
else:
get_ip_info = __get_ip_info_py3
class MOD(object):

View File

@ -30,11 +30,8 @@
__all__ = ['SMSd']
from time import localtime
from queue import Queue, Empty, Full
from .utils import *
if python_version < 3:
from Queue import Queue, Empty, Full
else:
from queue import Queue, Empty, Full
class SMSd(object):

View File

@ -31,7 +31,7 @@ from socket import inet_aton, inet_ntoa, inet_pton, inet_ntop, AF_INET, AF_INET6
from struct import pack
from array import array
from pycrate_core.utils import reverse_dict, log, python_version, str_types
from pycrate_core.utils import reverse_dict, log, str_types
from pycrate_core.elt import Envelope, Sequence, REPR_RAW, REPR_HEX, REPR_BIN, REPR_HUM
from pycrate_core.base import *
from pycrate_core.repr import *
@ -105,8 +105,7 @@ class IPAddr(Buf):
return val
def set_val(self, val):
if python_version == 2 and isinstance(val, unicode) \
or python_version > 2 and isinstance(val, str_types):
if isinstance(val, str_types):
self.encode(val)
else:
Buf.set_val(self, val)

View File

@ -3987,16 +3987,10 @@ def parse_ISUP(buf):
"""
if len(buf) < 3:
return None, 1
if python_version < 3:
try:
Msg = ISUPTypeClasses[ord(buf[2])]()
except:
return None, 1
else:
try:
Msg = ISUPTypeClasses[buf[2]]()
except:
return None, 1
try:
Msg = ISUPTypeClasses[buf[2]]()
except:
return None, 1
try:
Msg.from_bytes(buf)
except:

View File

@ -28,8 +28,6 @@
#*/
from pycrate_core.utils import *
if python_version < 3:
from struct import unpack
from .TS24008_IE import *
from .TS24008_MM import *
@ -103,18 +101,11 @@ def parse_NAS_MO(buf, inner=True):
element: Element instance, if err is null (no error)
element: None, if err is not null (standard NAS error code)
"""
if python_version < 3:
try:
pd, type = unpack('>BB', buf[:2])
except Exception:
# error 111, unspecified protocol error
return None, 111
else:
try:
pd, type = buf[0], buf[1]
except Exception:
# error 111, unspecified protocol error
return None, 111
try:
pd, type = buf[0], buf[1]
except Exception:
# error 111, unspecified protocol error
return None, 111
if pd & 0xf != 0xe:
# 4-bit protocol discriminator
pd &= 0xf
@ -155,24 +146,14 @@ def parse_NAS_MT(buf, inner=True, wl2=False):
element: Element instance, if err is null (no error)
element: None, if err is not null (standard NAS error code)
"""
if python_version < 3:
try:
if wl2:
pd, type = unpack('>BB', buf[1:3])
else:
pd, type = unpack('>BB', buf[:2])
except Exception:
# error 111, unspecified protocol error
return None, 111
else:
try:
if wl2:
pd, type = buf[1], buf[2]
else:
pd, type = buf[0], buf[1]
except Exception:
# error 111, unspecified protocol error
return None, 111
try:
if wl2:
pd, type = buf[1], buf[2]
else:
pd, type = buf[0], buf[1]
except Exception:
# error 111, unspecified protocol error
return None, 111
if pd & 0xf != 0xe:
# 4-bit protocol discriminator
pd &= 0xf

View File

@ -94,10 +94,7 @@ def parse_NAS5G(buf, inner=True, sec_hdr=True):
elif pd == 46:
# 5GSM
try:
if python_version < 3:
typ = ord(buf[3:4])
else:
typ = buf[3]
typ = buf[3]
except:
# error 111, unspecified protocol error
return None, 111

View File

@ -51,17 +51,10 @@ def parse_NASLTE_MO(buf, inner=True, sec_hdr=True):
element: Element instance, if err is null (no error)
element: None, if err is not null (standard LTE NAS error code)
"""
if python_version < 3:
try:
pd = ord(buf[:1])
except Exception:
# error 111, unspecified protocol error
return None, 111
else:
try:
pd = buf[0]
except Exception:
return None, 111
try:
pd = buf[0]
except Exception:
return None, 111
shdr = pd>>4
pd &= 0xf
@ -98,16 +91,10 @@ def parse_NASLTE_MO(buf, inner=True, sec_hdr=True):
#
if pd == 7:
# EMM
if python_version < 3:
try:
typ = ord(buf[1:2])
except Exception:
return None, 111
else:
try:
typ = buf[1]
except Exception:
return None, 111
try:
typ = buf[1]
except Exception:
return None, 111
try:
Msg = EMMTypeMOClasses[typ]()
except KeyError:
@ -115,16 +102,10 @@ def parse_NASLTE_MO(buf, inner=True, sec_hdr=True):
return None, 97
elif pd == 2:
# ESM
if python_version < 3:
try:
typ = ord(buf[2:3])
except Exception:
return None, 111
else:
try:
typ = buf[2]
except Exception:
return None, 111
try:
typ = buf[2]
except Exception:
return None, 111
try:
Msg = ESMTypeClasses[typ]()
except KeyError:
@ -184,17 +165,10 @@ def parse_NASLTE_MT(buf, inner=True, sec_hdr=True):
element: Element instance, if err is null (no error)
element: None, if err is not null (standard LTE NAS error code)
"""
if python_version < 3:
try:
pd = ord(buf[0])
except Exception:
# error 111, unspecified protocol error
return None, 111
else:
try:
pd = buf[0]
except Exception:
return None, 111
try:
pd = buf[0]
except Exception:
return None, 111
shdr = pd>>4
pd &= 0xf
@ -231,16 +205,10 @@ def parse_NASLTE_MT(buf, inner=True, sec_hdr=True):
#
if pd == 7:
# EMM
if python_version < 3:
try:
typ = ord(buf[1])
except Exception:
return None, 111
else:
try:
typ = buf[1]
except Exception:
return None, 111
try:
typ = buf[1]
except Exception:
return None, 111
try:
Msg = EMMTypeMTClasses[typ]()
except KeyError:
@ -248,16 +216,10 @@ def parse_NASLTE_MT(buf, inner=True, sec_hdr=True):
return None, 97
elif pd == 2:
# ESM
if python_version < 3:
try:
typ = ord(buf[2])
except Exception:
return None, 111
else:
try:
typ = buf[2]
except Exception:
return None, 111
try:
typ = buf[2]
except Exception:
return None, 111
try:
Msg = ESMTypeClasses[typ]()
except KeyError:

View File

@ -1568,16 +1568,10 @@ def parse_SCCP(buf, w_scmg=True):
"""
if not buf:
return None, 1
if python_version < 3:
try:
Msg = SCCPTypeClasses[ord(buf[0])]()
except:
return None, 1
else:
try:
Msg = SCCPTypeClasses[buf[0]]()
except:
return None, 1
try:
Msg = SCCPTypeClasses[buf[0]]()
except:
return None, 1
try:
Msg.from_bytes(buf)
except:
@ -1614,16 +1608,10 @@ def parse_SCMG(buf):
"""
if not buf:
return None, 1
if python_version < 3:
try:
Msg = SCMGTypeClasses[ord(buf[0])]()
except:
return None, 1
else:
try:
Msg = SCMGTypeClasses[buf[0]]()
except:
return None, 1
try:
Msg = SCMGTypeClasses[buf[0]]()
except:
return None, 1
try:
Msg.from_bytes(buf)
except:

View File

@ -1880,10 +1880,7 @@ def parse_GTPv0(buf):
"""
if len(buf) < 20:
return None, ERR_GTP_BUF_TOO_SHORT
if python_version < 3:
typ = ord(buf[1])
else:
typ = buf[1]
typ = buf[1]
try:
Msg = GTPv0Dispatcher[typ]()
except KeyError:

View File

@ -44,7 +44,7 @@ __all__ = [
# release 13 (d00)
#------------------------------------------------------------------------------#
from pycrate_core.utils import python_version, pack_val, TYPE_UINT, PycrateErr
from pycrate_core.utils import pack_val, TYPE_UINT, PycrateErr
from pycrate_core.charpy import Charpy
from pycrate_core.elt import Envelope
from pycrate_core.base import Uint
@ -574,10 +574,7 @@ def encode_7b(txt, off=0):
# check the length in bits and add padding bits
pad = ((8-(7*len(arr)+off)%8)%8)
arr.insert(0, (TYPE_UINT, 0, pad))
if python_version < 3:
return ''.join(reversed(pack_val(*arr)[0])), cnt
else:
return bytes(reversed(pack_val(*arr)[0])), cnt
return bytes(reversed(pack_val(*arr)[0])), cnt
def decode_7b(buf, off=0):
@ -590,10 +587,7 @@ def decode_7b(buf, off=0):
Returns:
decoded text string (utf8 str)
"""
if python_version < 3:
char = Charpy(''.join(reversed(buf)))
else:
char = Charpy(bytes(reversed(buf)))
char = Charpy(bytes(reversed(buf)))
# jump over the padding bits
# WNG: in case of 7 bits padding, we will have an @ at the end
chars_num = (8*len(buf)-off) // 7

View File

@ -80,8 +80,6 @@ def encode_bcd(dig):
def decode_bcd(buf):
if python_version < 3:
buf = [ord(c) for c in buf]
ret = []
for o in buf:
msb, lsb = o>>4, o&0xf
@ -162,10 +160,7 @@ class BufBCD(Buf):
def decode(self):
"""returns the encoded string of digits
"""
if python_version < 3:
num = [ord(c) for c in self.get_val()]
else:
num = self.get_val()
num = self.get_val()
ret = []
for o in num:
msb, lsb = o>>4, o&0xf
@ -192,10 +187,7 @@ class BufBCD(Buf):
if len(ret) % 2:
ret.append( self._filler )
#
if python_version < 3:
self._val = ''.join([chr(c) for c in map(lambda x,y:x+(y<<4), ret[::2], ret[1::2])])
else:
self._val = bytes(map(lambda x,y:x+(y<<4), ret[::2], ret[1::2]))
self._val = bytes(map(lambda x,y:x+(y<<4), ret[::2], ret[1::2]))
def repr(self):
# special hexdump representation
@ -288,33 +280,18 @@ class PLMN(Buf):
"""returns the encoded string of digits
"""
plmn = []
if python_version < 3:
for c in self.get_val():
b = ord(c)
plmn.append(b>>4)
plmn.append(b&0xf)
try:
if plmn[2] == 0xf:
return u'%i%i%i%i%i' % (plmn[1], plmn[0], plmn[3], plmn[5], plmn[4])
else:
return u'%i%i%i%i%i%i' % (plmn[1], plmn[0], plmn[3], plmn[5], plmn[4], plmn[2])
except IndexError:
# an invalid value has been set, _SAFE_STAT / DYN is probably disabled
# for e.g. fuzzing purpose, but there is still need to not break here
return '0x%s' % hexlify(self.to_bytes()).decode('ascii')
else:
for b in self.get_val():
plmn.append(b>>4)
plmn.append(b&0xf)
try:
if plmn[2] == 0xf:
return '%i%i%i%i%i' % (plmn[1], plmn[0], plmn[3], plmn[5], plmn[4])
else:
return '%i%i%i%i%i%i' % (plmn[1], plmn[0], plmn[3], plmn[5], plmn[4], plmn[2])
except IndexError:
# an invalid value has been set, _SAFE_STAT / DYN is probably disabled
# for e.g. fuzzing purpose, but there is still need to not break here
return '0x%s' % hexlify(self.to_bytes()).decode('ascii')
for b in self.get_val():
plmn.append(b>>4)
plmn.append(b&0xf)
try:
if plmn[2] == 0xf:
return '%i%i%i%i%i' % (plmn[1], plmn[0], plmn[3], plmn[5], plmn[4])
else:
return '%i%i%i%i%i%i' % (plmn[1], plmn[0], plmn[3], plmn[5], plmn[4], plmn[2])
except IndexError:
# an invalid value has been set, _SAFE_STAT / DYN is probably disabled
# for e.g. fuzzing purpose, but there is still need to not break here
return '0x%s' % hexlify(self.to_bytes()).decode('ascii')
def encode(self, plmn=u'00101'):
"""encode the given PLMN string and store the resulting buffer in

View File

@ -5449,10 +5449,7 @@ def parse_GTP_SGSN(buf):
"""
if len(buf) < 8:
return None, ERR_GTP_BUF_TOO_SHORT
if python_version < 3:
typ = ord(buf[1])
else:
typ = buf[1]
typ = buf[1]
try:
Msg = GTPDispatcherSGSN[typ]()
except KeyError:
@ -5484,10 +5481,7 @@ def parse_GTP_GGSN(buf):
"""
if len(buf) < 8:
return None, ERR_GTP_BUF_TOO_SHORT
if python_version < 3:
typ = ord(buf[1])
else:
typ = buf[1]
typ = buf[1]
try:
Msg = GTPDispatcherGGSN[typ]()
except KeyError:

View File

@ -6073,10 +6073,7 @@ def parse_PFCP(buf):
"""
if len(buf) < 8:
return None, ERR_PFCP_BUF_TOO_SHORT
if python_version < 3:
typ = ord(buf[1])
else:
typ = buf[1]
typ = buf[1]
try:
Msg = PFCPDispatcher[typ]()
except KeyError:

View File

@ -7587,12 +7587,9 @@ def parse_GTPC(buf):
"""
if len(buf) < 8:
return None, ERR_GTPC_BUF_TOO_SHORT
if python_version < 3:
type = ord(buf[1])
else:
type = buf[1]
typ = buf[1]
try:
Msg = GTPCDispatcher[type]()
Msg = GTPCDispatcher[typ]()
except KeyError:
return None, ERR_GTPC_TYPE_NONEXIST
try:

View File

@ -416,12 +416,9 @@ def parse_GTPU(buf):
"""
if len(buf) < 8:
return None, ERR_GTPU_BUF_TOO_SHORT
if python_version < 3:
type = ord(buf[1])
else:
type = buf[1]
typ = buf[1]
try:
Msg = GTPUDispatcher[type]()
Msg = GTPUDispatcher[typ]()
except KeyError:
return None, ERR_GTPU_TYPE_NONEXIST
try:

View File

@ -737,10 +737,7 @@ class RRHandoverFailure(Layer3):
def get_tbf(l3msg):
v = l3msg[2][0].get_val()
if isinstance(v, str_types):
if python_version:
return v[0] & 1
else:
return ord(v[0]) & 1
return v[0] & 1
elif isinstance(v, list):
return v[-1]
else:

View File

@ -8,14 +8,6 @@ from setuptools import setup, find_packages
VERSION = "0.5.5"
# get dependencies according to the Python version
if sys.version_info[0] == 2:
# Python2 requires enum34
install_reqs = ['enum34']
else:
install_reqs = []
# get long description from the README.md
with open(os.path.join(os.path.dirname(__file__), "README.md")) as fd:
long_description = fd.read()
@ -56,7 +48,7 @@ setup(
],
# potential dependencies
install_requires=install_reqs,
install_requires=[],
# optional dependencies
extras_require={

View File

@ -387,10 +387,7 @@ def test_elt_2():
t['res'].set_val(0)
t['L'].set_val(t['V'].get_bl())
if python_version < 3:
assert( repr(t) == "<TestTLV : <T [Tag] : 0b00000010 (Tag2)><F1 [Flag1] : 1><F2 [Flag2] : 1><res [Reserved] : 0><L [Length] : 104><V [Value] : 'default value'>>" )
else:
assert( repr(t) == "<TestTLV : <T [Tag] : 0b00000010 (Tag2)><F1 [Flag1] : 1><F2 [Flag2] : 1><res [Reserved] : 0><L [Length] : 104><V [Value] : b'default value'>>" )
assert( repr(t) == "<TestTLV : <T [Tag] : 0b00000010 (Tag2)><F1 [Flag1] : 1><F2 [Flag2] : 1><res [Reserved] : 0><L [Length] : 104><V [Value] : b'default value'>>" )
if _with_json:
jv = t._to_jval()
@ -400,10 +397,7 @@ def test_elt_2():
t.from_json(jso)
assert( t._to_jval() == jv )
if python_version < 3:
assert( repr(t) == "<TestTLV : <T [Tag] : 0b00000010 (Tag2)><F1 [Flag1] : 1><F2 [Flag2] : 1><res [Reserved] : 0><L [Length] : 104><V [Value] : 'default value'>>" )
else:
assert( repr(t) == "<TestTLV : <T [Tag] : 0b00000010 (Tag2)><F1 [Flag1] : 1><F2 [Flag2] : 1><res [Reserved] : 0><L [Length] : 104><V [Value] : b'default value'>>" )
assert( repr(t) == "<TestTLV : <T [Tag] : 0b00000010 (Tag2)><F1 [Flag1] : 1><F2 [Flag2] : 1><res [Reserved] : 0><L [Length] : 104><V [Value] : b'default value'>>" )
class TestTLV2(Envelope):