def setUp(self): self.c1 = constraint.ConstraintsIntersection( constraint.ValueRangeConstraint(1, 30)) self.c2 = constraint.ConstraintsIntersection( self.c1, constraint.ValueRangeConstraint(1, 20)) self.c2 = constraint.ConstraintsIntersection( self.c2, constraint.ValueRangeConstraint(1, 10))
def testSubtype(self): self.s1.clear() assert self.s1.subtype( implicitTag=tag.Tag(tag.tagClassPrivate, tag.tagFormatSimple, 2), subtypeSpec=constraint.SingleValueConstraint(1, 3), sizeSpec=constraint.ValueSizeConstraint(0, 1)) == self.s1.clone( tagSet=tag.TagSet( tag.Tag(tag.tagClassPrivate, tag.tagFormatSimple, 2)), subtypeSpec=constraint.ConstraintsIntersection( constraint.SingleValueConstraint(1, 3)), sizeSpec=constraint.ValueSizeConstraint(0, 1))
def testSubtype(self): assert univ.Integer().subtype( value=1, implicitTag=tag.Tag(tag.tagClassPrivate, tag.tagFormatSimple, 2), subtypeSpec=constraint.SingleValueConstraint( 1, 3)) == univ.Integer( value=1, tagSet=tag.TagSet( tag.Tag(tag.tagClassPrivate, tag.tagFormatSimple, 2)), subtypeSpec=constraint.ConstraintsIntersection( constraint.SingleValueConstraint(1, 3)))
class Asn1ItemBase(Asn1Item): # Set of tags for this ASN.1 type tagSet = tag.TagSet() # A list of constraint.Constraint instances for checking values subtypeSpec = constraint.ConstraintsIntersection() # Used for ambiguous ASN.1 types identification typeId = None def __init__(self, tagSet=None, subtypeSpec=None): if tagSet is None: self._tagSet = self.tagSet else: self._tagSet = tagSet if subtypeSpec is None: self._subtypeSpec = self.subtypeSpec else: self._subtypeSpec = subtypeSpec def _verifySubtypeSpec(self, value, idx=None): try: self._subtypeSpec(value, idx) except error.PyAsn1Error: c, i, t = sys.exc_info() raise c('%s at %s' % (i, self.__class__.__name__)) def getSubtypeSpec(self): return self._subtypeSpec def getTagSet(self): return self._tagSet def getEffectiveTagSet(self): return self._tagSet # used by untagged types def getTagMap(self): return tagmap.TagMap({self._tagSet: self}) def isSameTypeWith(self, other, matchTags=True, matchConstraints=True): return self is other or \ (not matchTags or \ self._tagSet == other.getTagSet()) and \ (not matchConstraints or \ self._subtypeSpec==other.getSubtypeSpec()) def isSuperTypeOf(self, other, matchTags=True, matchConstraints=True): """Returns true if argument is a ASN1 subtype of ourselves""" return (not matchTags or \ self._tagSet.isSuperTagSetOf(other.getTagSet())) and \ (not matchConstraints or \ (self._subtypeSpec.isSuperTypeOf(other.getSubtypeSpec())))
class Asn1ItemBase(Asn1Item): # Set of tags for this ASN.1 type tagSet = () # A list of constraint.Constraint instances for checking values subtypeSpec = constraint.ConstraintsIntersection() def __init__(self, tagSet=None, subtypeSpec=None): if tagSet is None: self._tagSet = self.tagSet else: self._tagSet = tagSet if subtypeSpec is None: self._subtypeSpec = self.subtypeSpec else: self._subtypeSpec = subtypeSpec def _verifySubtypeSpec(self, value, idx=None): self._subtypeSpec(value, idx) def getSubtypeSpec(self): return self._subtypeSpec def getTagSet(self): return self._tagSet def getTypeMap(self): return {self._tagSet: self} def isSameTypeWith(self, other): return self is other or \ self._tagSet == other.getTagSet() and \ self._subtypeSpec == other.getSubtypeSpec() def isSuperTypeOf(self, other): """Returns true if argument is a ASN1 subtype of ourselves""" return self._tagSet.isSuperTagSetOf(other.getTagSet()) and \ self._subtypeSpec.isSuperTypeOf(other.getSubtypeSpec())
class Asn1ItemBase(Asn1Item): #: Default :py:class:`~pyasn1.type.tag.TagSet` object representing #: ASN.1 tag(s) associated with this ASN.1 type. tagSet = tag.TagSet() #: Default :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` #: object imposing constraints on initialization values. subtypeSpec = constraint.ConstraintsIntersection() # Used for ambiguous ASN.1 types identification typeId = None def __init__(self, tagSet=None, subtypeSpec=None): if tagSet is None: self._tagSet = self.tagSet else: self._tagSet = tagSet if subtypeSpec is None: self._subtypeSpec = self.subtypeSpec else: self._subtypeSpec = subtypeSpec def _verifySubtypeSpec(self, value, idx=None): try: self._subtypeSpec(value, idx) except error.PyAsn1Error: c, i, t = sys.exc_info() raise c('%s at %s' % (i, self.__class__.__name__)) def getSubtypeSpec(self): return self._subtypeSpec def getTagSet(self): return self._tagSet def getEffectiveTagSet(self): return self._tagSet # used by untagged types def getTagMap(self): return tagmap.TagMap({self._tagSet: self}) def isSameTypeWith(self, other, matchTags=True, matchConstraints=True): """Evaluates ASN.1 types for equality. Indicates if argument is an object of the same ASN.1 type as the calling type or not. ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints (:py:mod:`~pyasn1.type.constraint`) are considered when carrying out ASN.1 types comparision. Parameters ---------- other: a pyasn1 type object Class instance representing ASN.1 type. Returns ------- : :class:`bool` :class:`True` if types are the same, :class:`False` otherwise. Note ---- No Python inheritance relationship between pyasn1 objects is considered. """ return self is other or \ (not matchTags or self._tagSet == other.getTagSet()) and \ (not matchConstraints or self._subtypeSpec == other.getSubtypeSpec()) def isSuperTypeOf(self, other, matchTags=True, matchConstraints=True): """Evaluates ASN.1 types for relationship. Indicates if argument is an ASN.1 type that is derived from the ASN.1 type of the calling type. ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints (:py:mod:`~pyasn1.type.constraint`) are considered when carrying out ASN.1 types comparision. Parameters ---------- other: a pyasn1 type object Class instance representing ASN.1 type. Returns ------- : :class:`bool` :class:`True` if argument is derived from the calling type, :class:`False` otherwise. Note ---- No Python inheritance relationship between pyasn1 objects is considered. """ return (not matchTags or self._tagSet.isSuperTagSetOf(other.getTagSet())) and \ (not matchConstraints or (self._subtypeSpec.isSuperTypeOf(other.getSubtypeSpec()))) @staticmethod def isNoValue(*values): for value in values: if value is not None and value is not noValue: return False return True
class AbstractConstructedAsn1Item(Asn1ItemBase): componentType = None sizeSpec = constraint.ConstraintsIntersection() def __init__(self, componentType=None, tagSet=None, subtypeSpec=None, sizeSpec=None): Asn1ItemBase.__init__(self, tagSet, subtypeSpec) if componentType is None: self._componentType = self.componentType else: self._componentType = componentType if sizeSpec is None: self._sizeSpec = self.sizeSpec else: self._sizeSpec = sizeSpec self._componentValues = [] self._componentValuesSet = 0 def __repr__(self): r = self.__class__.__name__ + '()' for idx in range(len(self._componentValues)): if self._componentValues[idx] is None: continue r = r + '.setComponentByPosition(%s, %r)' % ( idx, self._componentValues[idx]) return r def __eq__(self, other): return self is other and True or self._componentValues == other def __ne__(self, other): return self._componentValues != other def __lt__(self, other): return self._componentValues < other def __le__(self, other): return self._componentValues <= other def __gt__(self, other): return self._componentValues > other def __ge__(self, other): return self._componentValues >= other if sys.version_info[0] <= 2: def __nonzero__(self): return bool(self._componentValues) else: def __bool__(self): return bool(self._componentValues) def getComponentTagMap(self): raise error.PyAsn1Error('Method not implemented') def _cloneComponentValues(self, myClone, cloneValueFlag): pass def clone(self, tagSet=None, subtypeSpec=None, sizeSpec=None, cloneValueFlag=None): if tagSet is None: tagSet = self._tagSet if subtypeSpec is None: subtypeSpec = self._subtypeSpec if sizeSpec is None: sizeSpec = self._sizeSpec r = self.__class__(self._componentType, tagSet, subtypeSpec, sizeSpec) if cloneValueFlag: self._cloneComponentValues(r, cloneValueFlag) return r def subtype(self, implicitTag=None, explicitTag=None, subtypeSpec=None, sizeSpec=None, cloneValueFlag=None): 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 sizeSpec is None: sizeSpec = self._sizeSpec else: sizeSpec = sizeSpec + self._sizeSpec r = self.__class__(self._componentType, tagSet, subtypeSpec, sizeSpec) if cloneValueFlag: self._cloneComponentValues(r, cloneValueFlag) return r def _verifyComponent(self, idx, value): pass def verifySizeSpec(self): self._sizeSpec(self) def getComponentByPosition(self, idx): raise error.PyAsn1Error('Method not implemented') def setComponentByPosition(self, idx, value, verifyConstraints=True): raise error.PyAsn1Error('Method not implemented') def getComponentType(self): return self._componentType def __getitem__(self, idx): return self.getComponentByPosition(idx) def __setitem__(self, idx, value): self.setComponentByPosition(idx, value) def __len__(self): return len(self._componentValues) def clear(self): self._componentValues = [] self._componentValuesSet = 0 def setDefaultComponents(self): pass
class Gender(char.PrintableString): subtypeSpec = constraint.ConstraintsIntersection( constraint.ValueSizeConstraint(1, 1), constraint.SingleValueConstraint('M', 'F', 'm', 'f') )
def setUp(self): self.c1 = constraint.ConstraintsIntersection( constraint.ValueRangeConstraint(1, 9), constraint.ValueRangeConstraint(2, 5))
def testCmp4(self): c = constraint.ConstraintsUnion( constraint.ConstraintsIntersection( constraint.SingleValueConstraint(5))) assert self.c1 not in c, '__cmp__() fails'
def testCmp3(self): c = constraint.ConstraintsUnion( constraint.ConstraintsIntersection( constraint.SingleValueConstraint(4), constraint.ValueRangeConstraint(2, 4))) assert self.c1 in c, '__cmp__() fails'
def setUp(self): self.c1 = constraint.ConstraintsIntersection( constraint.SingleValueConstraint(4), constraint.ValueRangeConstraint(2, 4))
class ConstructedAsn1Type(Asn1Type): """Base class for all constructed classes representing ASN.1 types. ASN.1 distinguishes types by their ability to hold other objects. Those "nesting" types are known as *constructed* in ASN.1. In the user code, |ASN.1| class is normally used only for telling ASN.1 objects from others. Note ---- For as long as ASN.1 is concerned, a way to compare ASN.1 types is to use :meth:`isSameTypeWith` and :meth:`isSuperTypeOf` methods. """ #: If :obj:`True`, requires exact component type matching, #: otherwise subtype relation is only enforced strictConstraints = False componentType = None # backward compatibility, unused sizeSpec = constraint.ConstraintsIntersection() def __init__(self, **kwargs): readOnly = { 'componentType': self.componentType, # backward compatibility, unused 'sizeSpec': self.sizeSpec } # backward compatibility: preserve legacy sizeSpec support kwargs = self._moveSizeSpec(**kwargs) readOnly.update(kwargs) Asn1Type.__init__(self, **readOnly) def _moveSizeSpec(self, **kwargs): # backward compatibility, unused sizeSpec = kwargs.pop('sizeSpec', self.sizeSpec) if sizeSpec: subtypeSpec = kwargs.pop('subtypeSpec', self.subtypeSpec) if subtypeSpec: subtypeSpec = sizeSpec else: subtypeSpec += sizeSpec kwargs['subtypeSpec'] = subtypeSpec return kwargs def __repr__(self): representation = '%s %s object' % ( self.__class__.__name__, self.isValue and 'value' or 'schema') for attr, value in self.readOnly.items(): if value is not noValue: representation += ', %s=%r' % (attr, value) if self.isValue and self.components: representation += ', payload [%s]' % ', '.join( [repr(x) for x in self.components]) return '<%s>' % representation def __eq__(self, other): return self is other or self.components == other def __ne__(self, other): return self.components != other def __lt__(self, other): return self.components < other def __le__(self, other): return self.components <= other def __gt__(self, other): return self.components > other def __ge__(self, other): return self.components >= other if sys.version_info[0] <= 2: def __nonzero__(self): return bool(self.components) else: def __bool__(self): return bool(self.components) @property def components(self): raise error.PyAsn1Error('Method not implemented') def _cloneComponentValues(self, myClone, cloneValueFlag): pass def clone(self, **kwargs): """Create a modified version of |ASN.1| schema object. The `clone()` method accepts the same set arguments as |ASN.1| class takes on instantiation except that all arguments of the `clone()` method are optional. Whatever arguments are supplied, they are used to create a copy of `self` taking precedence over the ones used to instantiate `self`. Possible values of `self` are never copied over thus `clone()` can only create a new schema object. Returns ------- : new instance of |ASN.1| type/value Note ---- Due to the mutable nature of the |ASN.1| object, even if no arguments are supplied, a new |ASN.1| object will be created and returned. """ cloneValueFlag = kwargs.pop('cloneValueFlag', False) initializers = self.readOnly.copy() initializers.update(kwargs) clone = self.__class__(**initializers) if cloneValueFlag: self._cloneComponentValues(clone, cloneValueFlag) return clone def subtype(self, **kwargs): """Create a specialization of |ASN.1| schema object. The `subtype()` method accepts the same set arguments as |ASN.1| class takes on instantiation except that all parameters of the `subtype()` method are optional. With the exception of the arguments described below, the rest of supplied arguments they are used to create a copy of `self` taking precedence over the ones used to instantiate `self`. The following arguments to `subtype()` create a ASN.1 subtype out of |ASN.1| type. Other Parameters ---------------- implicitTag: :py:class:`~pyasn1.type.tag.Tag` Implicitly apply given ASN.1 tag object to `self`'s :py:class:`~pyasn1.type.tag.TagSet`, then use the result as new object's ASN.1 tag(s). explicitTag: :py:class:`~pyasn1.type.tag.Tag` Explicitly apply given ASN.1 tag object to `self`'s :py:class:`~pyasn1.type.tag.TagSet`, then use the result as new object's ASN.1 tag(s). subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Add ASN.1 constraints object to one of the `self`'s, then use the result as new object's ASN.1 constraints. Returns ------- : new instance of |ASN.1| type/value Note ---- Due to the mutable nature of the |ASN.1| object, even if no arguments are supplied, a new |ASN.1| object will be created and returned. """ initializers = self.readOnly.copy() cloneValueFlag = kwargs.pop('cloneValueFlag', False) implicitTag = kwargs.pop('implicitTag', None) if implicitTag is not None: initializers['tagSet'] = self.tagSet.tagImplicitly(implicitTag) explicitTag = kwargs.pop('explicitTag', None) if explicitTag is not None: initializers['tagSet'] = self.tagSet.tagExplicitly(explicitTag) for arg, option in kwargs.items(): initializers[arg] += option clone = self.__class__(**initializers) if cloneValueFlag: self._cloneComponentValues(clone, cloneValueFlag) return clone def getComponentByPosition(self, idx): raise error.PyAsn1Error('Method not implemented') def setComponentByPosition(self, idx, value, verifyConstraints=True): raise error.PyAsn1Error('Method not implemented') def setComponents(self, *args, **kwargs): for idx, value in enumerate(args): self[idx] = value for k in kwargs: self[k] = kwargs[k] return self # backward compatibility def setDefaultComponents(self): pass def getComponentType(self): return self.componentType # backward compatibility, unused def verifySizeSpec(self): self.subtypeSpec(self)
class AbstractConstructedAsn1Item(Asn1ItemBase): componentType = None sizeSpec = constraint.ConstraintsIntersection() def __init__(self, componentType=None, tagSet=None, subtypeSpec=None, sizeSpec=None): Asn1ItemBase.__init__(self, tagSet, subtypeSpec) if componentType is None: self._componentType = self.componentType else: self._componentType = componentType if sizeSpec is None: self._sizeSpec = self.sizeSpec else: self._sizeSpec = sizeSpec self._componentValues = [] self._componentValuesSet = 0 def __repr__(self): r = [] if self._componentType is not self.componentType: r.append('componentType=%r' % (self._componentType, )) if self._tagSet is not self.tagSet: r.append('tagSet=%r' % (self._tagSet, )) if self._subtypeSpec is not self.subtypeSpec: r.append('subtypeSpec=%r' % (self._subtypeSpec, )) r = '%s(%s)' % (self.__class__.__name__, ', '.join(r)) if self._componentValues: r += '.setComponents(%s)' % ', '.join( [repr(x) for x in self._componentValues]) return r def __eq__(self, other): return self is other and True or self._componentValues == other def __ne__(self, other): return self._componentValues != other def __lt__(self, other): return self._componentValues < other def __le__(self, other): return self._componentValues <= other def __gt__(self, other): return self._componentValues > other def __ge__(self, other): return self._componentValues >= other if sys.version_info[0] <= 2: def __nonzero__(self): return bool(self._componentValues) else: def __bool__(self): return bool(self._componentValues) def getComponentTagMap(self): raise error.PyAsn1Error('Method not implemented') def _cloneComponentValues(self, myClone, cloneValueFlag): pass def clone(self, tagSet=None, subtypeSpec=None, sizeSpec=None, cloneValueFlag=None): if tagSet is None: tagSet = self._tagSet if subtypeSpec is None: subtypeSpec = self._subtypeSpec if sizeSpec is None: sizeSpec = self._sizeSpec r = self.__class__(self._componentType, tagSet, subtypeSpec, sizeSpec) if cloneValueFlag: self._cloneComponentValues(r, cloneValueFlag) return r def subtype(self, implicitTag=None, explicitTag=None, subtypeSpec=None, sizeSpec=None, cloneValueFlag=None): 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 = self._subtypeSpec + subtypeSpec if sizeSpec is None: sizeSpec = self._sizeSpec else: sizeSpec = sizeSpec + self._sizeSpec r = self.__class__(self._componentType, tagSet, subtypeSpec, sizeSpec) if cloneValueFlag: self._cloneComponentValues(r, cloneValueFlag) return r def _verifyComponent(self, idx, value): pass def verifySizeSpec(self): self._sizeSpec(self) def getComponentByPosition(self, idx): raise error.PyAsn1Error('Method not implemented') def setComponentByPosition(self, idx, value, verifyConstraints=True): raise error.PyAsn1Error('Method not implemented') def setComponents(self, *args, **kwargs): for idx in range(len(args)): self[idx] = args[idx] for k in kwargs: self[k] = kwargs[k] return self def getComponentType(self): return self._componentType def setDefaultComponents(self): pass def __getitem__(self, idx): return self.getComponentByPosition(idx) def __setitem__(self, idx, value): self.setComponentByPosition(idx, value) def __len__(self): return len(self._componentValues) def clear(self): self._componentValues = [] self._componentValuesSet = 0
JWTClaimConstraints.sizeSpec = univ.Sequence.sizeSpec + constraint.ValueSizeConstraint( 1, 2) id_pe_JWTClaimConstraints = _OID(1, 3, 6, 1, 5, 5, 7, 1, 27) class ServiceProviderCode(char.IA5String): pass class TelephoneNumber(char.IA5String): pass TelephoneNumber.subtypeSpec = constraint.ConstraintsIntersection( constraint.ValueSizeConstraint(1, 15), constraint.PermittedAlphabetConstraint('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '#', '*')) class TelephoneNumberRange(univ.Sequence): pass TelephoneNumberRange.componentType = namedtype.NamedTypes( namedtype.NamedType('start', TelephoneNumber()), namedtype.NamedType( 'count', univ.Integer().subtype( subtypeSpec=constraint.ValueRangeConstraint(2, MAX))))
class Choice(Set): tagSet = tag.TagSet() # untagged sizeSpec = constraint.ConstraintsIntersection( constraint.ValueSizeConstraint(1, 1)) def __cmp__(self, other): if self._componentValues: return cmp(self._componentValues[self._currentIdx], other) return -1 def verifySizeSpec(self): self._sizeSpec(' ' * int(self.getComponent() is not None) # hackerish XXX ) def _cloneComponentValues(self, myClone, cloneValueFlag): try: c = self.getComponent() except error.PyAsn1Error: pass else: tagSet = getattr(c, 'getEffectiveTagSet', c.getTagSet)() if isinstance(c, base.AbstractConstructedAsn1Item): myClone.setComponentByType( tagSet, c.clone(cloneValueFlag=cloneValueFlag)) else: myClone.setComponentByType(tagSet, c.clone()) def setComponentByPosition(self, idx, value=None): l = len(self._componentValues) if idx >= l: self._componentValues = self._componentValues + (idx - l + 1) * [None] if hasattr(self, '_currentIdx'): self._componentValues[self._currentIdx] = None if value is None: if self._componentValues[idx] is None: self._componentValues[ idx] = self._componentType.getTypeByPosition(idx).clone() self._currentIdx = idx return self elif type(value) != types.InstanceType: value = self._componentType.getTypeByPosition(idx).clone( value=value) if self._componentType: self._verifyComponent(idx, value) self._verifySubtypeSpec(value, idx) self._componentValues[idx] = value self._currentIdx = idx return self def getMinTagSet(self): if self._tagSet: return self._tagSet else: return self._componentType.genMinTagSet() def getEffectiveTagSet(self): if self._tagSet: return self._tagSet else: c = self.getComponent() return getattr(c, 'getEffectiveTagSet', c.getTagSet)() def getTypeMap(self): if self._tagSet: return Set.getTypeMap(self) else: return Set.getComponentTypeMap(self) def getComponent(self, innerFlag=0): if hasattr(self, '_currentIdx'): c = self._componentValues[self._currentIdx] if innerFlag and hasattr(c, 'getComponent'): return c.getComponent(innerFlag) else: return c else: raise error.PyAsn1Error('Component not chosen') def getName(self, innerFlag=0): if hasattr(self, '_currentIdx'): if innerFlag: c = self._componentValues[self._currentIdx] if hasattr(c, 'getComponent'): return c.getName(innerFlag) return self._componentType.getNameByPosition(self._currentIdx) else: raise error.PyAsn1Error('Component not chosen') def setDefaultComponents(self): pass
class Asn1ItemBase(Asn1Item): #: Set or return a :py:class:`~pyasn1.type.tag.TagSet` object representing #: ASN.1 tag(s) associated with |ASN.1| type. tagSet = tag.TagSet() #: Default :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` #: object imposing constraints on initialization values. subtypeSpec = constraint.ConstraintsIntersection() # Disambiguation ASN.1 types identification typeId = None def __init__(self, **kwargs): for key in ('tagSet', 'subtypeSpec'): if key not in kwargs: kwargs[key] = getattr(self, key) for key, value in kwargs.items(): setattr(self, key, value) self.readOnly = key def __setattr__(self, name, value): if not name.startswith('_'): try: if name in self._readOnly: raise error.PyAsn1Error( 'read-only instance attribute "%s"' % name) except AttributeError: pass super(Asn1ItemBase, self).__setattr__(name, value) def __getReadOnly(self): try: return self._readOnly except AttributeError: self._readOnly = set() return frozenset(self._readOnly) def __setReadOnly(self, value): try: self._readOnly.add(value) except AttributeError: self._readOnly = set() self._readOnly.add(value) # property.setter is only available past Python 2.5 readOnly = property(__getReadOnly, __setReadOnly) @property def effectiveTagSet(self): """For |ASN.1| type is equivalent to *tagSet* """ return self.tagSet # used by untagged types @property def tagMap(self): """Return a :class:`~pyasn1.type.tagmap.TagMap` object mapping ASN.1 tags to ASN.1 objects within callee object. """ try: return self._tagMap except AttributeError: self._tagMap = tagmap.TagMap({self.tagSet: self}) return self._tagMap def isSameTypeWith(self, other, matchTags=True, matchConstraints=True): """Examine |ASN.1| type for equality with other ASN.1 type. ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints (:py:mod:`~pyasn1.type.constraint`) are examined when carrying out ASN.1 types comparison. No Python inheritance relationship between PyASN1 objects is considered. Parameters ---------- other: a pyasn1 type object Class instance representing ASN.1 type. Returns ------- : :class:`bool` :class:`True` if *other* is |ASN.1| type, :class:`False` otherwise. """ return self is other or \ (not matchTags or self.tagSet == other.tagSet) and \ (not matchConstraints or self.subtypeSpec == other.subtypeSpec) def isSuperTypeOf(self, other, matchTags=True, matchConstraints=True): """Examine |ASN.1| type for subtype relationship with other ASN.1 type. ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints (:py:mod:`~pyasn1.type.constraint`) are examined when carrying out ASN.1 types comparison. No Python inheritance relationship between PyASN1 objects is considered. Parameters ---------- other: a pyasn1 type object Class instance representing ASN.1 type. Returns ------- : :class:`bool` :class:`True` if *other* is a subtype of |ASN.1| type, :class:`False` otherwise. """ return (not matchTags or self.tagSet.isSuperTagSetOf(other.tagSet)) and \ (not matchConstraints or (self.subtypeSpec.isSuperTypeOf(other.subtypeSpec))) @staticmethod def isNoValue(*values): for value in values: if value is not None and value is not noValue: return False return True # backward compatibility def getTagSet(self): return self.tagSet def getEffectiveTagSet(self): return self.effectiveTagSet def getTagMap(self): return self.tagMap def getSubtypeSpec(self): return self.subtypeSpec def hasValue(self): return self.isValue
class Asn1ItemBase(Asn1Item): #: Default :py:class:`~pyasn1.type.tag.TagSet` object representing #: ASN.1 tag(s) associated with this ASN.1 type. tagSet = tag.TagSet() #: Default :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` #: object imposing constraints on initialization values. subtypeSpec = constraint.ConstraintsIntersection() # Used for ambiguous ASN.1 types identification typeId = None def __init__(self, tagSet=None, subtypeSpec=None): if tagSet is None: self._tagSet = self.tagSet else: self._tagSet = tagSet if subtypeSpec is None: self._subtypeSpec = self.subtypeSpec else: self._subtypeSpec = subtypeSpec def getSubtypeSpec(self): return self._subtypeSpec def getTagSet(self): return self._tagSet def getEffectiveTagSet(self): return self._tagSet # used by untagged types def getTagMap(self): return tagmap.TagMap({self._tagSet: self}) def isSameTypeWith(self, other, matchTags=True, matchConstraints=True): """Examine |ASN.1| type for equality with other ASN.1 type. ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints (:py:mod:`~pyasn1.type.constraint`) are examined when carrying out ASN.1 types comparison. No Python inheritance relationship between PyASN1 objects is considered. Parameters ---------- other: a pyasn1 type object Class instance representing ASN.1 type. Returns ------- : :class:`bool` :class:`True` if *other* is |ASN.1| type, :class:`False` otherwise. """ return self is other or \ (not matchTags or self._tagSet == other.getTagSet()) and \ (not matchConstraints or self._subtypeSpec == other.getSubtypeSpec()) def isSuperTypeOf(self, other, matchTags=True, matchConstraints=True): """Examine |ASN.1| type for subtype relationship with other ASN.1 type. ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints (:py:mod:`~pyasn1.type.constraint`) are examined when carrying out ASN.1 types comparison. No Python inheritance relationship between PyASN1 objects is considered. Parameters ---------- other: a pyasn1 type object Class instance representing ASN.1 type. Returns ------- : :class:`bool` :class:`True` if *other* is a subtype of |ASN.1| type, :class:`False` otherwise. """ return (not matchTags or self._tagSet.isSuperTagSetOf(other.getTagSet())) and \ (not matchConstraints or (self._subtypeSpec.isSuperTypeOf(other.getSubtypeSpec()))) @staticmethod def isNoValue(*values): for value in values: if value is not None and value is not noValue: return False return True
class AbstractConstructedAsn1Item(Asn1ItemBase): componentType = None sizeSpec = constraint.ConstraintsIntersection() def __init__(self, componentType=None, tagSet=None, subtypeSpec=None, sizeSpec=None): Asn1ItemBase.__init__(self, tagSet, subtypeSpec) if componentType is None: self._componentType = self.componentType else: self._componentType = componentType if sizeSpec is None: self._sizeSpec = self.sizeSpec else: self._sizeSpec = sizeSpec self._componentValues = [] def __repr__(self): r = self.__class__.__name__ + '()' for idx in range(len(self)): if self._componentValues[idx] is None: continue r = r + '.setComponentByPosition(%s, %s)' % ( idx, repr(self._componentValues[idx])) return r def __cmp__(self, other): return cmp(self._componentValues, other) def getComponentTypeMap(self): raise error.PyAsn1Error('Method not implemented') def _cloneComponentValues(self, myClone, cloneValueFlag): pass def clone(self, tagSet=None, subtypeSpec=None, sizeSpec=None, cloneValueFlag=None): if tagSet is None: tagSet = self._tagSet if subtypeSpec is None: subtypeSpec = self._subtypeSpec if sizeSpec is None: sizeSpec = self._sizeSpec r = self.__class__(self._componentType, tagSet, subtypeSpec, sizeSpec) if cloneValueFlag: self._cloneComponentValues(r, cloneValueFlag) return r def subtype(self, implicitTag=None, explicitTag=None, subtypeSpec=None, sizeSpec=None, cloneValueFlag=None): 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 sizeSpec is None: sizeSpec = self._sizeSpec else: sizeSpec = sizeSpec + self._sizeSpec r = self.__class__(self._componentType, tagSet, subtypeSpec, sizeSpec) if cloneValueFlag: self._cloneComponentValues(r, cloneValueFlag) return r def _verifyComponent(self, idx, value): pass def verifySizeSpec(self): self._sizeSpec(self) def getComponentByPosition(self, idx): raise error.PyAsn1Error('Method not implemented') def setComponentByPosition(self, idx, value): raise error.PyAsn1Error('Method not implemented') def getComponentType(self): return self._componentType def __getitem__(self, idx): return self._componentValues[idx] def __len__(self): return len(self._componentValues) def clear(self): self._componentValues = []
class Asn1ItemBase(Asn1Item): #: Set or return a :py:class:`~pyasn1.type.tag.TagSet` object representing #: ASN.1 tag(s) associated with |ASN.1| type. tagSet = tag.TagSet() #: Default :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` #: object imposing constraints on initialization values. subtypeSpec = constraint.ConstraintsIntersection() # Disambiguation ASN.1 types identification typeId = None def __init__(self, **kwargs): readOnly = {'tagSet': self.tagSet, 'subtypeSpec': self.subtypeSpec} readOnly.update(kwargs) self.__dict__.update(readOnly) self._readOnly = readOnly def __setattr__(self, name, value): if name[0] != '_' and name in self._readOnly: raise error.PyAsn1Error('read-only instance attribute "%s"' % name) self.__dict__[name] = value def __str__(self): return self.prettyPrint() @property def readOnly(self): return self._readOnly @property def effectiveTagSet(self): """For |ASN.1| type is equivalent to *tagSet* """ return self.tagSet # used by untagged types @property def tagMap(self): """Return a :class:`~pyasn1.type.tagmap.TagMap` object mapping ASN.1 tags to ASN.1 objects within callee object. """ return tagmap.TagMap({self.tagSet: self}) def isSameTypeWith(self, other, matchTags=True, matchConstraints=True): """Examine |ASN.1| type for equality with other ASN.1 type. ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints (:py:mod:`~pyasn1.type.constraint`) are examined when carrying out ASN.1 types comparison. Python class inheritance relationship is NOT considered. Parameters ---------- other: a pyasn1 type object Class instance representing ASN.1 type. Returns ------- : :class:`bool` :class:`True` if *other* is |ASN.1| type, :class:`False` otherwise. """ return ( self is other or (not matchTags or self.tagSet == other.tagSet) and (not matchConstraints or self.subtypeSpec == other.subtypeSpec)) def isSuperTypeOf(self, other, matchTags=True, matchConstraints=True): """Examine |ASN.1| type for subtype relationship with other ASN.1 type. ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints (:py:mod:`~pyasn1.type.constraint`) are examined when carrying out ASN.1 types comparison. Python class inheritance relationship is NOT considered. Parameters ---------- other: a pyasn1 type object Class instance representing ASN.1 type. Returns ------- : :class:`bool` :class:`True` if *other* is a subtype of |ASN.1| type, :class:`False` otherwise. """ return (not matchTags or (self.tagSet.isSuperTagSetOf(other.tagSet)) and (not matchConstraints or self.subtypeSpec.isSuperTypeOf(other.subtypeSpec))) @staticmethod def isNoValue(*values): for value in values: if value is not noValue: return False return True def prettyPrint(self, scope=0): raise NotImplementedError() # backward compatibility def getTagSet(self): return self.tagSet def getEffectiveTagSet(self): return self.effectiveTagSet def getTagMap(self): return self.tagMap def getSubtypeSpec(self): return self.subtypeSpec def hasValue(self): return self.isValue
class Choice(Set): tagSet = baseTagSet = tag.TagSet() # untagged sizeSpec = constraint.ConstraintsIntersection( constraint.ValueSizeConstraint(1, 1)) typeId = 5 _currentIdx = None def __eq__(self, other): if self._componentValues: return self._componentValues[self._currentIdx] == other return NotImplemented def __ne__(self, other): if self._componentValues: return self._componentValues[self._currentIdx] != other return NotImplemented def __lt__(self, other): if self._componentValues: return self._componentValues[self._currentIdx] < other return NotImplemented def __le__(self, other): if self._componentValues: return self._componentValues[self._currentIdx] <= other return NotImplemented def __gt__(self, other): if self._componentValues: return self._componentValues[self._currentIdx] > other return NotImplemented def __ge__(self, other): if self._componentValues: return self._componentValues[self._currentIdx] >= other return NotImplemented if sys.version_info[0] <= 2: def __nonzero__(self): return bool(self._componentValues) else: def __bool__(self): return bool(self._componentValues) def __len__(self): return self._currentIdx is not None and 1 or 0 def verifySizeSpec(self): if self._currentIdx is None: raise error.PyAsn1Error('Component not chosen') else: self._sizeSpec(' ') def _cloneComponentValues(self, myClone, cloneValueFlag): try: c = self.getComponent() except error.PyAsn1Error: pass else: if isinstance(c, Choice): tagSet = c.getEffectiveTagSet() else: tagSet = c.getTagSet() if isinstance(c, base.AbstractConstructedAsn1Item): myClone.setComponentByType( tagSet, c.clone(cloneValueFlag=cloneValueFlag)) else: myClone.setComponentByType(tagSet, c.clone()) def setComponentByPosition(self, idx, value=None, verifyConstraints=True): l = len(self._componentValues) if idx >= l: self._componentValues = self._componentValues + (idx - l + 1) * [None] if self._currentIdx is not None: self._componentValues[self._currentIdx] = None if value is None: if self._componentValues[idx] is None: self._componentValues[ idx] = self._componentType.getTypeByPosition(idx).clone() self._componentValuesSet = 1 self._currentIdx = idx return self elif not isinstance(value, base.Asn1Item): value = self._componentType.getTypeByPosition(idx).clone( value=value) if verifyConstraints: if self._componentTypeLen: self._verifyComponent(idx, value) self._verifySubtypeSpec(value, idx) self._componentValues[idx] = value self._currentIdx = idx self._componentValuesSet = 1 return self def getMinTagSet(self): if self._tagSet: return self._tagSet else: return self._componentType.genMinTagSet() def getEffectiveTagSet(self): if self._tagSet: return self._tagSet else: c = self.getComponent() if isinstance(c, Choice): return c.getEffectiveTagSet() else: return c.getTagSet() def getTagMap(self): if self._tagSet: return Set.getTagMap(self) else: return Set.getComponentTagMap(self) def getComponent(self, innerFlag=0): if self._currentIdx is None: raise error.PyAsn1Error('Component not chosen') else: c = self._componentValues[self._currentIdx] if innerFlag and isinstance(c, Choice): return c.getComponent(innerFlag) else: return c def getName(self, innerFlag=0): if self._currentIdx is None: raise error.PyAsn1Error('Component not chosen') else: if innerFlag: c = self._componentValues[self._currentIdx] if isinstance(c, Choice): return c.getName(innerFlag) return self._componentType.getNameByPosition(self._currentIdx) def setDefaultComponents(self): pass
class Asn1ItemBase(Asn1Item): #: Set or return a :py:class:`~pyasn1.type.tag.TagSet` object representing #: ASN.1 tag(s) associated with |ASN.1| type. tagSet = tag.TagSet() #: Default :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` #: object imposing constraints on initialization values. subtypeSpec = constraint.ConstraintsIntersection() # Disambiguation ASN.1 types identification typeId = None def __init__(self, tagSet=None, subtypeSpec=None): if tagSet is None: self._tagSet = self.__class__.tagSet else: self._tagSet = tagSet if subtypeSpec is None: self._subtypeSpec = self.__class__.subtypeSpec else: self._subtypeSpec = subtypeSpec @property def effectiveTagSet(self): """For |ASN.1| type is equivalent to *tagSet* """ return self._tagSet # used by untagged types @property def tagMap(self): """Return a :class:`~pyasn1.type.tagmap.TagMap` object mapping ASN.1 tags to ASN.1 objects within callee object. """ try: return self._tagMap except AttributeError: self._tagMap = tagmap.TagMap({self._tagSet: self}) return self._tagMap def isSameTypeWith(self, other, matchTags=True, matchConstraints=True): """Examine |ASN.1| type for equality with other ASN.1 type. ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints (:py:mod:`~pyasn1.type.constraint`) are examined when carrying out ASN.1 types comparison. No Python inheritance relationship between PyASN1 objects is considered. Parameters ---------- other: a pyasn1 type object Class instance representing ASN.1 type. Returns ------- : :class:`bool` :class:`True` if *other* is |ASN.1| type, :class:`False` otherwise. """ return self is other or \ (not matchTags or self._tagSet == other.tagSet) and \ (not matchConstraints or self._subtypeSpec == other.subtypeSpec) def isSuperTypeOf(self, other, matchTags=True, matchConstraints=True): """Examine |ASN.1| type for subtype relationship with other ASN.1 type. ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints (:py:mod:`~pyasn1.type.constraint`) are examined when carrying out ASN.1 types comparison. No Python inheritance relationship between PyASN1 objects is considered. Parameters ---------- other: a pyasn1 type object Class instance representing ASN.1 type. Returns ------- : :class:`bool` :class:`True` if *other* is a subtype of |ASN.1| type, :class:`False` otherwise. """ return (not matchTags or self._tagSet.isSuperTagSetOf(other.tagSet)) and \ (not matchConstraints or (self._subtypeSpec.isSuperTypeOf(other.subtypeSpec))) @staticmethod def isNoValue(*values): for value in values: if value is not None and value is not noValue: return False return True # backward compatibility def getTagSet(self): return self.tagSet def getEffectiveTagSet(self): return self.effectiveTagSet def getTagMap(self): return self.tagMap def getSubtypeSpec(self): return self.subtypeSpec
class RelativeOID(base.SimpleAsn1Type): """Create |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.SimpleAsn1Type`, its objects are immutable and duck-type Python :class:`tuple` objects (tuple of non-negative integers). Keyword Args ------------ value: :class:`tuple`, :class:`str` or |ASN.1| object Python sequence of :class:`int` or :class:`str` literal or |ASN.1| object. If `value` is not given, schema object will be created. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s). Constraints verification for |ASN.1| type occurs automatically on object instantiation. Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer. Examples -------- .. code-block:: python class RelOID(RelativeOID): ''' ASN.1 specification: id-pad-null RELATIVE-OID ::= { 0 } id-pad-once RELATIVE-OID ::= { 5 6 } id-pad-twice RELATIVE-OID ::= { 5 6 7 } ''' id_pad_null = RelOID('0') id_pad_once = RelOID('5.6') id_pad_twice = id_pad_once + (7,) """ #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x0d)) #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object #: imposing constraints on |ASN.1| type initialization values. subtypeSpec = constraint.ConstraintsIntersection() # Optimization for faster codec lookup typeId = base.SimpleAsn1Type.getTypeId() 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): return len(self._value) def __getitem__(self, i): if i.__class__ is slice: return self.clone(self._value[i]) else: return self._value[i] def __iter__(self): return iter(self._value) def __contains__(self, value): return value in self._value def index(self, suboid): return self._value.index(suboid) def isPrefixOf(self, other): """Indicate if this |ASN.1| object is a prefix of other |ASN.1| object. Parameters ---------- other: |ASN.1| object |ASN.1| object Returns ------- : :class:`bool` :obj:`True` if this |ASN.1| object is a parent (e.g. prefix) of the other |ASN.1| object or :obj:`False` otherwise. """ l = len(self) if l <= len(other): if self._value[:l] == other[:l]: return True return False def prettyIn(self, value): if isinstance(value, RelativeOID): return tuple(value) elif isStringType(value): if '-' in value: raise error.PyAsn1Error( 'Malformed RELATIVE-OID %s at %s: %s' % (value, self.__class__.__name__, sys.exc_info()[1])) try: return tuple( [int(subOid) for subOid in value.split('.') if subOid]) except ValueError: raise error.PyAsn1Error( 'Malformed RELATIVE-OID %s at %s: %s' % (value, self.__class__.__name__, sys.exc_info()[1])) try: tupleOfInts = tuple( [int(subOid) for subOid in value if subOid >= 0]) except (ValueError, TypeError): raise error.PyAsn1Error( 'Malformed RELATIVE-OID %s at %s: %s' % (value, self.__class__.__name__, sys.exc_info()[1])) if len(tupleOfInts) == len(value): return tupleOfInts raise error.PyAsn1Error('Malformed RELATIVE-OID %s at %s' % (value, self.__class__.__name__)) def prettyOut(self, value): return '.'.join([str(x) for x in value])