codekingpro/portable-devtools
115k
1#2# This file is part of pyasn1 software.3#4# Copyright (c) 2005-2020, Ilya Etingof <etingof@gmail.com>5# License: https://pyasn1.readthedocs.io/en/latest/license.html6#7import warnings8 9from pyasn1 import debug10from pyasn1 import error11from pyasn1.compat import _MISSING12from pyasn1.type import base13from pyasn1.type import char14from pyasn1.type import tag15from pyasn1.type import univ16from pyasn1.type import useful17 18__all__ = ['decode']19 20LOG = debug.registerLoggee(__name__, flags=debug.DEBUG_DECODER)21 22 23class AbstractScalarPayloadDecoder(object):24 def __call__(self, pyObject, asn1Spec, decodeFun=None, **options):25 return asn1Spec.clone(pyObject)26 27 28class BitStringPayloadDecoder(AbstractScalarPayloadDecoder):29 def __call__(self, pyObject, asn1Spec, decodeFun=None, **options):30 return asn1Spec.clone(univ.BitString.fromBinaryString(pyObject))31 32 33class SequenceOrSetPayloadDecoder(object):34 def __call__(self, pyObject, asn1Spec, decodeFun=None, **options):35 asn1Value = asn1Spec.clone()36 37 componentsTypes = asn1Spec.componentType38 39 for field in asn1Value:40 if field in pyObject:41 asn1Value[field] = decodeFun(pyObject[field], componentsTypes[field].asn1Object, **options)42 43 return asn1Value44 45 46class SequenceOfOrSetOfPayloadDecoder(object):47 def __call__(self, pyObject, asn1Spec, decodeFun=None, **options):48 asn1Value = asn1Spec.clone()49 50 for pyValue in pyObject:51 asn1Value.append(decodeFun(pyValue, asn1Spec.componentType), **options)52 53 return asn1Value54 55 56class ChoicePayloadDecoder(object):57 def __call__(self, pyObject, asn1Spec, decodeFun=None, **options):58 asn1Value = asn1Spec.clone()59 60 componentsTypes = asn1Spec.componentType61 62 for field in pyObject:63 if field in componentsTypes:64 asn1Value[field] = decodeFun(pyObject[field], componentsTypes[field].asn1Object, **options)65 break66 67 return asn1Value68 69 70TAG_MAP = {71 univ.Integer.tagSet: AbstractScalarPayloadDecoder(),72 univ.Boolean.tagSet: AbstractScalarPayloadDecoder(),73 univ.BitString.tagSet: BitStringPayloadDecoder(),74 univ.OctetString.tagSet: AbstractScalarPayloadDecoder(),75 univ.Null.tagSet: AbstractScalarPayloadDecoder(),76 univ.ObjectIdentifier.tagSet: AbstractScalarPayloadDecoder(),77 univ.RelativeOID.tagSet: AbstractScalarPayloadDecoder(),78 univ.Enumerated.tagSet: AbstractScalarPayloadDecoder(),79 univ.Real.tagSet: AbstractScalarPayloadDecoder(),80 univ.Sequence.tagSet: SequenceOrSetPayloadDecoder(), # conflicts with SequenceOf81 univ.Set.tagSet: SequenceOrSetPayloadDecoder(), # conflicts with SetOf82 univ.Choice.tagSet: ChoicePayloadDecoder(), # conflicts with Any83 # character string types84 char.UTF8String.tagSet: AbstractScalarPayloadDecoder(),85 char.NumericString.tagSet: AbstractScalarPayloadDecoder(),86 char.PrintableString.tagSet: AbstractScalarPayloadDecoder(),87 char.TeletexString.tagSet: AbstractScalarPayloadDecoder(),88 char.VideotexString.tagSet: AbstractScalarPayloadDecoder(),89 char.IA5String.tagSet: AbstractScalarPayloadDecoder(),90 char.GraphicString.tagSet: AbstractScalarPayloadDecoder(),91 char.VisibleString.tagSet: AbstractScalarPayloadDecoder(),92 char.GeneralString.tagSet: AbstractScalarPayloadDecoder(),93 char.UniversalString.tagSet: AbstractScalarPayloadDecoder(),94 char.BMPString.tagSet: AbstractScalarPayloadDecoder(),95 # useful types96 useful.ObjectDescriptor.tagSet: AbstractScalarPayloadDecoder(),97 useful.GeneralizedTime.tagSet: AbstractScalarPayloadDecoder(),98 useful.UTCTime.tagSet: AbstractScalarPayloadDecoder()99}100 101# Put in ambiguous & non-ambiguous types for faster codec lookup102TYPE_MAP = {103 univ.Integer.typeId: AbstractScalarPayloadDecoder(),104 univ.Boolean.typeId: AbstractScalarPayloadDecoder(),105 univ.BitString.typeId: BitStringPayloadDecoder(),106 univ.OctetString.typeId: AbstractScalarPayloadDecoder(),107 univ.Null.typeId: AbstractScalarPayloadDecoder(),108 univ.ObjectIdentifier.typeId: AbstractScalarPayloadDecoder(),109 univ.RelativeOID.typeId: AbstractScalarPayloadDecoder(),110 univ.Enumerated.typeId: AbstractScalarPayloadDecoder(),111 univ.Real.typeId: AbstractScalarPayloadDecoder(),112 # ambiguous base types113 univ.Set.typeId: SequenceOrSetPayloadDecoder(),114 univ.SetOf.typeId: SequenceOfOrSetOfPayloadDecoder(),115 univ.Sequence.typeId: SequenceOrSetPayloadDecoder(),116 univ.SequenceOf.typeId: SequenceOfOrSetOfPayloadDecoder(),117 univ.Choice.typeId: ChoicePayloadDecoder(),118 univ.Any.typeId: AbstractScalarPayloadDecoder(),119 # character string types120 char.UTF8String.typeId: AbstractScalarPayloadDecoder(),121 char.NumericString.typeId: AbstractScalarPayloadDecoder(),122 char.PrintableString.typeId: AbstractScalarPayloadDecoder(),123 char.TeletexString.typeId: AbstractScalarPayloadDecoder(),124 char.VideotexString.typeId: AbstractScalarPayloadDecoder(),125 char.IA5String.typeId: AbstractScalarPayloadDecoder(),126 char.GraphicString.typeId: AbstractScalarPayloadDecoder(),127 char.VisibleString.typeId: AbstractScalarPayloadDecoder(),128 char.GeneralString.typeId: AbstractScalarPayloadDecoder(),129 char.UniversalString.typeId: AbstractScalarPayloadDecoder(),130 char.BMPString.typeId: AbstractScalarPayloadDecoder(),131 # useful types132 useful.ObjectDescriptor.typeId: AbstractScalarPayloadDecoder(),133 useful.GeneralizedTime.typeId: AbstractScalarPayloadDecoder(),134 useful.UTCTime.typeId: AbstractScalarPayloadDecoder()135}136 137 138class SingleItemDecoder(object):139 140 TAG_MAP = TAG_MAP141 TYPE_MAP = TYPE_MAP142 143 def __init__(self, tagMap=_MISSING, typeMap=_MISSING, **ignored):144 self._tagMap = tagMap if tagMap is not _MISSING else self.TAG_MAP145 self._typeMap = typeMap if typeMap is not _MISSING else self.TYPE_MAP146 147 def __call__(self, pyObject, asn1Spec, **options):148 149 if LOG:150 debug.scope.push(type(pyObject).__name__)151 LOG('decoder called at scope %s, working with '152 'type %s' % (debug.scope, type(pyObject).__name__))153 154 if asn1Spec is None or not isinstance(asn1Spec, base.Asn1Item):155 raise error.PyAsn1Error(156 'asn1Spec is not valid (should be an instance of an ASN.1 '157 'Item, not %s)' % asn1Spec.__class__.__name__)158 159 try:160 valueDecoder = self._typeMap[asn1Spec.typeId]161 162 except KeyError:163 # use base type for codec lookup to recover untagged types164 baseTagSet = tag.TagSet(asn1Spec.tagSet.baseTag, asn1Spec.tagSet.baseTag)165 166 try:167 valueDecoder = self._tagMap[baseTagSet]168 169 except KeyError:170 raise error.PyAsn1Error('Unknown ASN.1 tag %s' % asn1Spec.tagSet)171 172 if LOG:173 LOG('calling decoder %s on Python type %s '174 '<%s>' % (type(valueDecoder).__name__,175 type(pyObject).__name__, repr(pyObject)))176 177 value = valueDecoder(pyObject, asn1Spec, self, **options)178 179 if LOG:180 LOG('decoder %s produced ASN.1 type %s '181 '<%s>' % (type(valueDecoder).__name__,182 type(value).__name__, repr(value)))183 debug.scope.pop()184 185 return value186 187 188class Decoder(object):189 SINGLE_ITEM_DECODER = SingleItemDecoder190 191 def __init__(self, **options):192 self._singleItemDecoder = self.SINGLE_ITEM_DECODER(**options)193 194 def __call__(self, pyObject, asn1Spec=None, **kwargs):195 return self._singleItemDecoder(pyObject, asn1Spec=asn1Spec, **kwargs)196 197 198#: Turns Python objects of built-in types into ASN.1 objects.199#:200#: Takes Python objects of built-in types and turns them into a tree of201#: ASN.1 objects (e.g. :py:class:`~pyasn1.type.base.PyAsn1Item` derivative) which202#: may be a scalar or an arbitrary nested structure.203#:204#: Parameters205#: ----------206#: pyObject: :py:class:`object`207#: A scalar or nested Python objects208#:209#: Keyword Args210#: ------------211#: asn1Spec: any pyasn1 type object e.g. :py:class:`~pyasn1.type.base.PyAsn1Item` derivative212#: A pyasn1 type object to act as a template guiding the decoder. It is required213#: for successful interpretation of Python objects mapping into their ASN.1214#: representations.215#:216#: Returns217#: -------218#: : :py:class:`~pyasn1.type.base.PyAsn1Item` derivative219#: A scalar or constructed pyasn1 object220#:221#: Raises222#: ------223#: ~pyasn1.error.PyAsn1Error224#: On decoding errors225#:226#: Examples227#: --------228#: Decode native Python object into ASN.1 objects with ASN.1 schema229#:230#: .. code-block:: pycon231#:232#: >>> seq = SequenceOf(componentType=Integer())233#: >>> s, _ = decode([1, 2, 3], asn1Spec=seq)234#: >>> str(s)235#: SequenceOf:236#: 1 2 3237#:238decode = Decoder()239 240def __getattr__(attr: str):241 if newAttr := {"tagMap": "TAG_MAP", "typeMap": "TYPE_MAP"}.get(attr):242 warnings.warn(f"{attr} is deprecated. Please use {newAttr} instead.", DeprecationWarning, stacklevel=2)243 return globals()[newAttr]244 raise AttributeError(attr)245 