def setUp(self): self.ts1 = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 12) ) self.ts2 = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 12) )
class SetOf(base.AbstractConstructedAsn1Item): componentType = None tagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x11)) def _cloneComponentValues(self, myClone, cloneValueFlag): idx = 0 l = len(self._componentValues) while idx < l: c = self._componentValues[idx] if c is not None: if isinstance(c, base.AbstractConstructedAsn1Item): myClone.setComponentByPosition( idx, c.clone(cloneValueFlag=cloneValueFlag)) else: myClone.setComponentByPosition(idx, c.clone()) idx = idx + 1 def _verifyComponent(self, idx, value): if self._componentType is not None and \ not self._componentType.isSuperTypeOf(value): raise error.PyAsn1Error('Component type error %s' % value) def getComponentByPosition(self, idx): return self._componentValues[idx] def setComponentByPosition(self, idx, value=None): l = len(self._componentValues) if idx >= l: self._componentValues = self._componentValues + (idx - l + 1) * [None] if value is None: if self._componentValues[idx] is None: if self._componentType is None: raise error.PyAsn1Error('Component type not defined') self._componentValues[idx] = self._componentType.clone() return self elif type(value) != types.InstanceType: if self._componentType is None: raise error.PyAsn1Error('Component type not defined') if isinstance(self._componentType, base.AbstractSimpleAsn1Item): value = self._componentType.clone(value=value) else: raise error.PyAsn1Error('Instance value required') if self._componentType is not None: self._verifyComponent(idx, value) self._verifySubtypeSpec(value, idx) self._componentValues[idx] = value return self def getComponentTypeMap(self): if self._componentType is not None: return self._componentType.getTypeMap() def prettyPrint(self, scope=0): scope = scope + 1 r = self.__class__.__name__ + ':\n' for idx in range(len(self._componentValues)): r = r + ' ' * scope + self._componentValues[idx].prettyPrint(scope) return r
def to_asn1(self): task = asn1.SkrAbonentsTask(tagSet=(tag.initTagSet( tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 1)))) body = task.getComponentByName('validate-identifiers') for item in self.items: choice = asn1.SkrRequestedAbonentsParameters() if isinstance(item, operations.LogicalOperation): choice.setComponentByName('separator', item.code) else: component = choice.getComponentByName('find-mask') if isinstance(item, RequestedPerson): predicate = asn1.SkrRequestedPerson() item.copy_to(predicate) component.setComponentByName( 'id', asn1.sorm_request_abonent_person) component.setComponentByName( 'data', univ.Any(der_encode(predicate))) else: if isinstance(item, RequestedOrganization): predicate = asn1.SkrRequestedOrganization() item.copy_to(predicate) component.setComponentByName( 'id', asn1.sorm_request_abonent_organization) component.setComponentByName( 'data', univ.Any(der_encode(predicate))) else: raise exceptions.GeneralFault( 'an invalid object type "{0}" in the "{1}" class'. format(item.__class__.__name__, self.__class__.__name__)) body.append(choice) return task
def encode_data(self): reqs = asn1.SkrAdjustmentRequest(tagSet=(tag.initTagSet( tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 2)))) tools.copy_list_to_sequence_of( reqs.getComponentByName('supports'), self.supports, lambda item: useful.ObjectDescriptor(item)) return der_encode(reqs)
class Set(SequenceAndSetBase): tagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x11)) def getComponentByType(self, tagSet, innerFlag=0): c = self.getComponentByPosition( self._componentType.getPositionByType(tagSet)) if innerFlag and hasattr(c, 'getComponent'): # get inner component by inner tagSet return c.getComponent(1) else: # get outer component by inner tagSet return c def setComponentByType(self, tagSet, value=None, innerFlag=0): idx = self._componentType.getPositionByType(tagSet) t = self._componentType.getTypeByPosition(idx) if innerFlag: # set inner component by inner tagSet if t.getTagSet(): self.setComponentByPosition(idx, value) else: t = self.setComponentByPosition(idx).getComponentByPosition( idx) t.setComponentByType(tagSet, value, innerFlag) else: # set outer component by inner tagSet self.setComponentByPosition(idx, value) def getComponentTypeMap(self): return self._componentType.getTypeMap(1) def getComponentPositionByType(self, tagSet): return self._componentType.getPositionByType(tagSet)
def to_asn1(self): task = asn1.SkrConnectionsTask(tagSet=(tag.initTagSet( tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 2)))) body = task.getComponentByName(self.component_name) for item in self.items: choice = asn1.SkrRequestedConnectionParameter() if isinstance(item, operations.LogicalOperation): choice.setComponentByName('separator', item.code) else: component = choice.getComponentByName('find-mask') descriptor = tagged_components.get(item.__class__.__name__, None) if descriptor is None: raise exceptions.GeneralFault( f'unable to construct connection request ' + f'item by the "{item.__class__.__name__}" class') component.setComponentByName('id', descriptor[0]) if isinstance(item, base.ASN1Constructable): component.setComponentByName( 'data', univ.Any(der_encode(item.to_asn1()))) else: if isinstance(item, base.ASN1Copyable): predicate = descriptor[1]() item.copy_to(predicate) component.setComponentByName( 'data', univ.Any(der_encode(predicate))) else: raise exceptions.GeneralFault( f'unable to encode predicate item ' + f'by the "{item.__class__.__name__}" class') body.append(choice) return task
class Sequence(SequenceAndSetBase): tagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x10)) def getComponentTypeMapNearPosition(self, idx): return self._componentType.getTypeMapNearPosition(idx) def getComponentPositionNearType(self, tagSet, idx): return self._componentType.getPositionNearType(tagSet, idx)
def to_asn1(self): return asn1.SkrDataContentTask( (self.data_content_id), tagSet=( tag.initTagSet( tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 9) ) ) )
def encode_data(self): reqs = asn1.SkrTrap(tagSet=(tag.initTagSet( tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0)))) reqs['trap-type'] = self.type if self.trap_message is not None: reqs['trap-message'] = self.trap_message if self.reference_message is not None: reqs['reference-message'] = self.reference_message return der_encode(reqs)
def encode_data(self): ack = asn1.SkrAcknowledgement(tagSet=(tag.initTagSet( tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 1)))) ack.setComponentByName('successful', self.successful) if self.broken_record is not None: ack.setComponentByName('broken-record', self.broken_record) if self.error_description is not None: ack.setComponentByName('error-description', self.error_description) return der_encode(ack)
class ObjectIdentifier(base.AbstractSimpleAsn1Item): tagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x06)) def __add__(self, other): return self.clone(self._value + other) def __radd__(self, other): return self.clone(other + self._value) # Sequence object protocol def __len__(self): return len(self._value) def __getitem__(self, i): if type(i) == types.SliceType: return self.clone(operator.getslice(self._value, i.start, i.stop)) else: return self._value[i] # They won't be defined if version is at least 2.0 final if base.version_info < (2, 0): def __getslice__(self, i, j): return self[max(0, i):max(0, j):] def index(self, suboid): return self._value.index(suboid) def isPrefixOf(self, value): """Returns true if argument OID resides deeper in the OID tree""" l = len(self._value) if l <= len(value): if self._value[:l] == value[:l]: return 1 return 0 def prettyIn(self, value): """Dotted -> tuple of numerics OID converter""" if type(value) is types.TupleType: return value if type(value) is not types.StringType: return tuple(value) r = [] for element in filter(None, string.split(value, '.')): try: r.append(string.atoi(element, 0)) except string.atoi_error: try: r.append(string.atol(element, 0)) except string.atol_error, why: raise error.PyAsn1Error( 'Malformed Object ID %s at %s: %s' % (str(value), self.__class__.__name__, why)) return tuple(r)
def encode_data(self): reqs = asn1.SkrDataInterruptRequest( value=(self.task_id), tagSet=( tag.initTagSet( tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 6) ) ) ) return der_encode(reqs)
def encode_data(self): reqs = asn1.SkrDataLoadRequest( value=self.task_id, tagSet=( tag.initTagSet( tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 2) ) ) ) return der_encode(reqs)
def to_asn1(self): task = asn1.SkrDictionaryTask( tagSet=( tag.initTagSet( tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0) ) ) ) task['id'] = self.id task['data'] = self.data return task
class EndOfOctets(base.AbstractSimpleAsn1Item): defaultValue = 0 tagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x00)) _instance = None def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = object.__new__(cls, *args, **kwargs) return cls._instance
def to_asn1(self): task = asn1.SkrAbonentsTask(tagSet=(tag.initTagSet( tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 1)))) body = task.getComponentByName('validate-services') for item in self.items: choice = asn1.SkrValidateServicesParameters() if isinstance(item, operations.LogicalOperation): choice.setComponentByName('separator', item.code) else: component = choice.getComponentByName('find-mask') if isinstance(item, str): component.setComponentByName('contract', item) else: if isinstance( item, identifiers.RequestedPagerIdentifier ) or isinstance( item, identifiers.RequestedPstnIdentifier) or isinstance( item, identifiers.RequestedGsmIdentifier ) or isinstance( item, identifiers.RequestedCdmaIdentifier ) or isinstance( item, identifiers.RequestedVoipIdentifier ) or isinstance( item, identifiers.RequestedDataNetworkIdentifier): identifier = asn1.SkrRequestedIdentifier( tagSet=(tag.initTagSet( tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 1)))) item.copy_to(identifier) component.setComponentByName('identifier', identifier) else: raise exceptions.GeneralFault( 'an invalid object type "{0}" in the "{1}" class'. format(item.__class__.__name__, self.__class__.__name__)) body.append(choice) return task
def to_asn1(self): task = asn1.SkrAbonentsTask(tagSet=(tag.initTagSet( tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 1)))) body = task.getComponentByName('validate-abonents-task') for item in self.items: choice = asn1.SkrRequestedIdentifierParameters() if isinstance(item, operations.LogicalOperation): choice.setComponentByName('separator', item.code) else: item.copy_to(choice.getComponentByName('find-mask')) body.append(choice) return task
def encode_data(self): reqs = asn1.SkrCreateTaskRequest(tagSet=(tag.initTagSet( tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 8)))) if self.telco_codes is not None: tools.copy_list_to_sequence_of(reqs.getComponentByName('telcos'), self.telco_codes) if self.range is not None: self.range.copy_to(reqs.getComponentByName('range')) if self.report_limit is not None: reqs.setComponentByName('report-limit', self.report_limit) task_body = self.task.to_asn1() reqs.getComponentByName('task').setComponentByType( task_body.getTagSet(), task_body) return der_encode(reqs)
class Set(SequenceAndSetBase): tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x11) ) typeId = 4 def getComponent(self, innerFlag=0): return self def getComponentByType(self, tagSet, innerFlag=0): c = self.getComponentByPosition( self._componentType.getPositionByType(tagSet) ) if innerFlag and isinstance(c, Set): # get inner component by inner tagSet return c.getComponent(1) else: # get outer component by inner tagSet return c def setComponentByType(self, tagSet, value=None, innerFlag=0, verifyConstraints=True): idx = self._componentType.getPositionByType(tagSet) t = self._componentType.getTypeByPosition(idx) if innerFlag: # set inner component by inner tagSet if t.getTagSet(): return self.setComponentByPosition( idx, value, verifyConstraints ) else: t = self.setComponentByPosition(idx).getComponentByPosition(idx) return t.setComponentByType( tagSet, value, innerFlag, verifyConstraints ) else: # set outer component by inner tagSet return self.setComponentByPosition( idx, value, verifyConstraints ) def getComponentTagMap(self): if self._componentType: return self._componentType.getTagMap(True) def getComponentPositionByType(self, tagSet): if self._componentType: return self._componentType.getPositionByType(tagSet)
class OctetString(base.AbstractSimpleAsn1Item): tagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x04)) def prettyOut(self, value): return str(value) def prettyIn(self, value): return str(value) # Immutable sequence object protocol def __len__(self): return len(self._value) def __getitem__(self, i): if type(i) == types.SliceType: return self.clone(operator.getslice(self._value, i.start, i.stop)) else: return self._value[i] def __add__(self, value): return self.clone(self._value + value) def __radd__(self, value): return self.clone(value + self._value) def __mul__(self, value): return self.clone(self._value * value) def __rmul__(self, value): return self.__mul__(value) # They won't be defined if version is at least 2.0 final if base.version_info < (2, 0): def __getslice__(self, i, j): return self[max(0, i):max(0, j):]
def encode_data(self): reqs = asn1.SkrConnectRequest(tagSet=(tag.initTagSet( tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0)))) reqs['session-timeout'] = 60 reqs['max-data-length'] = 1000 reqs['data-packet-window-size'] = 5 reqs['data-load-timeout'] = 60 reqs['request-response-timeout'] = 60 reqs['data-packet-response-timeout'] = 60 reqs.getComponentByName( 'session-timeout')._value = self.session_timeout reqs.getComponentByName( 'max-data-length')._value = self.max_data_length reqs.getComponentByName( 'data-packet-window-size')._value = self.data_packet_window_size reqs.getComponentByName( 'data-load-timeout')._value = self.data_load_timeout reqs.getComponentByName( 'request-response-timeout')._value = self.request_response_timeout reqs.getComponentByName('data-packet-response-timeout' )._value = self.data_packet_response_timeout return der_encode(reqs)
class EndOfOctets(base.AbstractSimpleAsn1Item): defaultValue = 0 tagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x00))
class SequenceOf(SetOf): tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x10)) typeId = 2
class Enumerated(Integer): tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x0A))
class Real(base.AbstractSimpleAsn1Item): try: _plusInf = float('inf') _minusInf = float('-inf') _inf = (_plusInf, _minusInf) except ValueError: # Infinity support is platform and Python dependent _plusInf = _minusInf = None _inf = () tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x09)) def __normalizeBase10(self, value): m, b, e = value while m and m % 10 == 0: m = m / 10 e = e + 1 return m, b, e def prettyIn(self, value): if isinstance(value, tuple) and len(value) == 3: for d in value: if not isinstance(d, intTypes): raise error.PyAsn1Error('Lame Real value syntax: %s' % (value, )) if value[1] not in (2, 10): raise error.PyAsn1Error('Prohibited base for Real value: %s' % (value[1], )) if value[1] == 10: value = self.__normalizeBase10(value) return value elif isinstance(value, intTypes): return self.__normalizeBase10((value, 10, 0)) elif isinstance(value, float): if self._inf and value in self._inf: return value else: e = 0 while int(value) != value: value = value * 10 e = e - 1 return self.__normalizeBase10((int(value), 10, e)) elif isinstance(value, Real): return tuple(value) elif isinstance(value, str): # handle infinite literal try: return float(value) except ValueError: pass raise error.PyAsn1Error('Bad real value syntax: %s' % (value, )) def prettyOut(self, value): if value in self._inf: return '\'%s\'' % value else: return str(value) def isPlusInfinity(self): return self._value == self._plusInf def isMinusInfinity(self): return self._value == self._minusInf def isInfinity(self): return self._value in self._inf def __str__(self): return str(float(self)) def __add__(self, value): return self.clone(float(self) + value) def __radd__(self, value): return self + value def __mul__(self, value): return self.clone(float(self) * value) def __rmul__(self, value): return self * value def __sub__(self, value): return self.clone(float(self) - value) def __rsub__(self, value): return self.clone(value - float(self)) def __mod__(self, value): return self.clone(float(self) % value) def __rmod__(self, value): return self.clone(value % float(self)) def __pow__(self, value, modulo=None): return self.clone(pow(float(self), value, modulo)) def __rpow__(self, value): return self.clone(pow(value, float(self))) if sys.version_info[0] <= 2: def __div__(self, value): return self.clone(float(self) / value) def __rdiv__(self, value): return self.clone(value / float(self)) else: def __truediv__(self, value): return self.clone(float(self) / value) def __rtruediv__(self, value): return self.clone(value / float(self)) def __divmod__(self, value): return self.clone(float(self) // value) def __rdivmod__(self, value): return self.clone(value // float(self)) def __int__(self): return int(float(self)) if sys.version_info[0] <= 2: def __long__(self): return long(float(self)) def __float__(self): if self._value in self._inf: return self._value else: return float(self._value[0] * pow(self._value[1], self._value[2])) def __abs__(self): return abs(float(self)) def __lt__(self, value): return float(self) < value def __le__(self, value): return float(self) <= value def __eq__(self, value): return float(self) == value def __ne__(self, value): return float(self) != value def __gt__(self, value): return float(self) > value def __ge__(self, value): return float(self) >= value if sys.version_info[0] <= 2: def __nonzero__(self): return bool(float(self)) else: def __bool__(self): return bool(float(self)) __hash__ = base.AbstractSimpleAsn1Item.__hash__ def __getitem__(self, idx): if self._value in self._inf: raise error.PyAsn1Error('Invalid infinite value operation') else: return self._value[idx]
class ObjectIdentifier(base.AbstractSimpleAsn1Item): tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x06)) def __add__(self, other): return self.clone(self._value + other) def __radd__(self, other): return self.clone(other + self._value) def asTuple(self): return self._value # Sequence object protocol def __len__(self): if self._len is None: self._len = len(self._value) return self._len def __getitem__(self, i): if isinstance(i, slice): return self.clone(operator.getitem(self._value, i)) else: return self._value[i] def __str__(self): return self.prettyPrint() def index(self, suboid): return self._value.index(suboid) def isPrefixOf(self, value): """Returns true if argument OID resides deeper in the OID tree""" l = len(self) if l <= len(value): if self._value[:l] == value[:l]: return 1 return 0 def prettyIn(self, value): """Dotted -> tuple of numerics OID converter""" if isinstance(value, tuple): pass elif isinstance(value, ObjectIdentifier): return tuple(value) elif isinstance(value, str): r = [] for element in [x for x in value.split('.') if x != '']: try: r.append(int(element, 0)) except ValueError: raise error.PyAsn1Error( 'Malformed Object ID %s at %s: %s' % (str(value), self.__class__.__name__, sys.exc_info()[1])) value = tuple(r) else: try: value = tuple(value) except TypeError: raise error.PyAsn1Error( 'Malformed Object ID %s at %s: %s' % (str(value), self.__class__.__name__, sys.exc_info()[1])) for x in value: if not isinstance(x, intTypes) or x < 0: raise error.PyAsn1Error('Invalid sub-ID in %s at %s' % (value, self.__class__.__name__)) return value def prettyOut(self, value): return '.'.join([str(x) for x in value])
class Null(OctetString): defaultValue = ''.encode() # This is tightly constrained tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x05)) subtypeSpec = OctetString.subtypeSpec + constraint.SingleValueConstraint( ''.encode())
class OctetString(base.AbstractSimpleAsn1Item): tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x04)) defaultBinValue = defaultHexValue = base.noValue encoding = 'us-ascii' def __init__(self, value=None, tagSet=None, subtypeSpec=None, encoding=None, binValue=None, hexValue=None): if encoding is None: self._encoding = self.encoding else: self._encoding = encoding if binValue is not None: value = self.fromBinaryString(binValue) if hexValue is not None: value = self.fromHexString(hexValue) if value is None or value is base.noValue: value = self.defaultHexValue if value is None or value is base.noValue: value = self.defaultBinValue self.__intValue = None base.AbstractSimpleAsn1Item.__init__(self, value, tagSet, subtypeSpec) def clone(self, value=None, tagSet=None, subtypeSpec=None, encoding=None, binValue=None, hexValue=None): if value is None and tagSet is None and subtypeSpec is None and \ encoding is None and binValue is None and hexValue is None: return self if value is None and binValue is None and hexValue is None: value = self._value if tagSet is None: tagSet = self._tagSet if subtypeSpec is None: subtypeSpec = self._subtypeSpec if encoding is None: encoding = self._encoding return self.__class__(value, tagSet, subtypeSpec, encoding, binValue, hexValue) if sys.version_info[0] <= 2: def prettyIn(self, value): if isinstance(value, str): return value elif isinstance(value, (tuple, list)): try: return ''.join([chr(x) for x in value]) except ValueError: raise error.PyAsn1Error( 'Bad OctetString initializer \'%s\'' % (value, )) else: return str(value) else: def prettyIn(self, value): if isinstance(value, bytes): return value elif isinstance(value, OctetString): return value.asOctets() elif isinstance(value, (tuple, list, map)): try: return bytes(value) except ValueError: raise error.PyAsn1Error( 'Bad OctetString initializer \'%s\'' % (value, )) else: try: return str(value).encode(self._encoding) except UnicodeEncodeError: raise error.PyAsn1Error( 'Can\'t encode string \'%s\' with \'%s\' codec' % (value, self._encoding)) def fromBinaryString(self, value): bitNo = 8 byte = 0 r = () for v in value: if bitNo: bitNo = bitNo - 1 else: bitNo = 7 r = r + (byte, ) byte = 0 if v == '0': v = 0 elif v == '1': v = 1 else: raise error.PyAsn1Error( 'Non-binary OCTET STRING initializer %s' % (v, )) byte = byte | (v << bitNo) return octets.ints2octs(r + (byte, )) def fromHexString(self, value): r = p = () for v in value: if p: r = r + (int(p + v, 16), ) p = () else: p = v if p: r = r + (int(p + '0', 16), ) return octets.ints2octs(r) def prettyOut(self, value): if sys.version_info[0] <= 2: numbers = tuple([ord(x) for x in value]) else: numbers = tuple(value) if [x for x in numbers if x < 32 or x > 126]: return '0x' + ''.join(['%.2x' % x for x in numbers]) else: return str(value) def __repr__(self): if self._value is base.noValue: return self.__class__.__name__ + '()' if [x for x in self.asNumbers() if x < 32 or x > 126]: return self.__class__.__name__ + '(hexValue=\'' + ''.join( ['%.2x' % x for x in self.asNumbers()]) + '\')' else: return self.__class__.__name__ + '(\'' + self.prettyOut( self._value) + '\')' if sys.version_info[0] <= 2: def __str__(self): return str(self._value) def __unicode__(self): return self._value.decode(self._encoding, 'ignore') def asOctets(self): return self._value def asNumbers(self): if self.__intValue is None: self.__intValue = tuple([ord(x) for x in self._value]) return self.__intValue else: def __str__(self): return self._value.decode(self._encoding, 'ignore') def __bytes__(self): return self._value def asOctets(self): return self._value def asNumbers(self): if self.__intValue is None: self.__intValue = tuple(self._value) return self.__intValue # Immutable sequence object protocol def __len__(self): if self._len is None: self._len = len(self._value) return self._len def __getitem__(self, i): if isinstance(i, slice): return self.clone(operator.getitem(self._value, i)) else: return self._value[i] def __add__(self, value): return self.clone(self._value + self.prettyIn(value)) def __radd__(self, value): return self.clone(self.prettyIn(value) + self._value) def __mul__(self, value): return self.clone(self._value * value) def __rmul__(self, value): return self * value
class BitString(base.AbstractSimpleAsn1Item): tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x03)) namedValues = namedval.NamedValues() def __init__(self, value=None, tagSet=None, subtypeSpec=None, namedValues=None): if namedValues is None: self.__namedValues = self.namedValues else: self.__namedValues = namedValues base.AbstractSimpleAsn1Item.__init__(self, value, tagSet, subtypeSpec) def clone(self, value=None, tagSet=None, subtypeSpec=None, namedValues=None): if value is None and tagSet is None and subtypeSpec is None \ and namedValues is None: return self if value is None: value = self._value if tagSet is None: tagSet = self._tagSet if subtypeSpec is None: subtypeSpec = self._subtypeSpec if namedValues is None: namedValues = self.__namedValues return self.__class__(value, tagSet, subtypeSpec, namedValues) def subtype(self, value=None, implicitTag=None, explicitTag=None, subtypeSpec=None, namedValues=None): if value is None: value = self._value if implicitTag is not None: tagSet = self._tagSet.tagImplicitly(implicitTag) elif explicitTag is not None: tagSet = self._tagSet.tagExplicitly(explicitTag) else: tagSet = self._tagSet if subtypeSpec is None: subtypeSpec = self._subtypeSpec else: subtypeSpec = subtypeSpec + self._subtypeSpec if namedValues is None: namedValues = self.__namedValues else: namedValues = namedValues + self.__namedValues return self.__class__(value, tagSet, subtypeSpec, namedValues) def __str__(self): return str(tuple(self)) # Immutable sequence object protocol def __len__(self): if self._len is None: self._len = len(self._value) return self._len def __getitem__(self, i): if isinstance(i, slice): return self.clone(operator.getitem(self._value, i)) else: return self._value[i] def __add__(self, value): return self.clone(self._value + value) def __radd__(self, value): return self.clone(value + self._value) def __mul__(self, value): return self.clone(self._value * value) def __rmul__(self, value): return self * value def prettyIn(self, value): r = [] if not value: return () elif isinstance(value, str): if value[0] == '\'': if value[-2:] == '\'B': for v in value[1:-2]: if v == '0': r.append(0) elif v == '1': r.append(1) else: raise error.PyAsn1Error( 'Non-binary BIT STRING initializer %s' % (v, )) return tuple(r) elif value[-2:] == '\'H': for v in value[1:-2]: i = 4 v = int(v, 16) while i: i = i - 1 r.append((v >> i) & 0x01) return tuple(r) else: raise error.PyAsn1Error( 'Bad BIT STRING value notation %s' % (value, )) else: for i in value.split(','): j = self.__namedValues.getValue(i) if j is None: raise error.PyAsn1Error( 'Unknown bit identifier \'%s\'' % (i, )) if j >= len(r): r.extend([0] * (j - len(r) + 1)) r[j] = 1 return tuple(r) elif isinstance(value, (tuple, list)): r = tuple(value) for b in r: if b and b != 1: raise error.PyAsn1Error( 'Non-binary BitString initializer \'%s\'' % (r, )) return r elif isinstance(value, BitString): return tuple(value) else: raise error.PyAsn1Error('Bad BitString initializer type \'%s\'' % (value, )) def prettyOut(self, value): return '\"\'%s\'B\"' % ''.join([str(x) for x in value])
class Boolean(Integer): tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x01), ) subtypeSpec = Integer.subtypeSpec + constraint.SingleValueConstraint(0, 1) namedValues = Integer.namedValues.clone(('False', 0), ('True', 1))