Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

univ.py 98KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061
  1. #
  2. # This file is part of pyasn1 software.
  3. #
  4. # Copyright (c) 2005-2018, Ilya Etingof <etingof@gmail.com>
  5. # License: http://snmplabs.com/pyasn1/license.html
  6. #
  7. import math
  8. import sys
  9. from pyasn1 import error
  10. from pyasn1.codec.ber import eoo
  11. from pyasn1.compat import binary
  12. from pyasn1.compat import integer
  13. from pyasn1.compat import octets
  14. from pyasn1.type import base
  15. from pyasn1.type import constraint
  16. from pyasn1.type import namedtype
  17. from pyasn1.type import namedval
  18. from pyasn1.type import tag
  19. from pyasn1.type import tagmap
  20. NoValue = base.NoValue
  21. noValue = NoValue()
  22. __all__ = ['Integer', 'Boolean', 'BitString', 'OctetString', 'Null',
  23. 'ObjectIdentifier', 'Real', 'Enumerated',
  24. 'SequenceOfAndSetOfBase', 'SequenceOf', 'SetOf',
  25. 'SequenceAndSetBase', 'Sequence', 'Set', 'Choice', 'Any',
  26. 'NoValue', 'noValue']
  27. # "Simple" ASN.1 types (yet incomplete)
  28. class Integer(base.AbstractSimpleAsn1Item):
  29. """Create |ASN.1| type or object.
  30. |ASN.1| objects are immutable and duck-type Python :class:`int` objects.
  31. Keyword Args
  32. ------------
  33. value: :class:`int`, :class:`str` or |ASN.1| object
  34. Python integer or string literal or |ASN.1| class instance.
  35. tagSet: :py:class:`~pyasn1.type.tag.TagSet`
  36. Object representing non-default ASN.1 tag(s)
  37. subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
  38. Object representing non-default ASN.1 subtype constraint(s)
  39. namedValues: :py:class:`~pyasn1.type.namedval.NamedValues`
  40. Object representing non-default symbolic aliases for numbers
  41. Raises
  42. ------
  43. :py:class:`~pyasn1.error.PyAsn1Error`
  44. On constraint violation or bad initializer.
  45. Examples
  46. --------
  47. .. code-block:: python
  48. class ErrorCode(Integer):
  49. '''
  50. ASN.1 specification:
  51. ErrorCode ::=
  52. INTEGER { disk-full(1), no-disk(-1),
  53. disk-not-formatted(2) }
  54. error ErrorCode ::= disk-full
  55. '''
  56. namedValues = NamedValues(
  57. ('disk-full', 1), ('no-disk', -1),
  58. ('disk-not-formatted', 2)
  59. )
  60. error = ErrorCode('disk-full')
  61. """
  62. #: Set (on class, not on instance) or return a
  63. #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s)
  64. #: associated with |ASN.1| type.
  65. tagSet = tag.initTagSet(
  66. tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x02)
  67. )
  68. #: Set (on class, not on instance) or return a
  69. #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object
  70. #: imposing constraints on |ASN.1| type initialization values.
  71. subtypeSpec = constraint.ConstraintsIntersection()
  72. #: Default :py:class:`~pyasn1.type.namedval.NamedValues` object
  73. #: representing symbolic aliases for numbers
  74. namedValues = namedval.NamedValues()
  75. # Optimization for faster codec lookup
  76. typeId = base.AbstractSimpleAsn1Item.getTypeId()
  77. def __init__(self, value=noValue, **kwargs):
  78. if 'namedValues' not in kwargs:
  79. kwargs['namedValues'] = self.namedValues
  80. base.AbstractSimpleAsn1Item.__init__(self, value, **kwargs)
  81. def __and__(self, value):
  82. return self.clone(self._value & value)
  83. def __rand__(self, value):
  84. return self.clone(value & self._value)
  85. def __or__(self, value):
  86. return self.clone(self._value | value)
  87. def __ror__(self, value):
  88. return self.clone(value | self._value)
  89. def __xor__(self, value):
  90. return self.clone(self._value ^ value)
  91. def __rxor__(self, value):
  92. return self.clone(value ^ self._value)
  93. def __lshift__(self, value):
  94. return self.clone(self._value << value)
  95. def __rshift__(self, value):
  96. return self.clone(self._value >> value)
  97. def __add__(self, value):
  98. return self.clone(self._value + value)
  99. def __radd__(self, value):
  100. return self.clone(value + self._value)
  101. def __sub__(self, value):
  102. return self.clone(self._value - value)
  103. def __rsub__(self, value):
  104. return self.clone(value - self._value)
  105. def __mul__(self, value):
  106. return self.clone(self._value * value)
  107. def __rmul__(self, value):
  108. return self.clone(value * self._value)
  109. def __mod__(self, value):
  110. return self.clone(self._value % value)
  111. def __rmod__(self, value):
  112. return self.clone(value % self._value)
  113. def __pow__(self, value, modulo=None):
  114. return self.clone(pow(self._value, value, modulo))
  115. def __rpow__(self, value):
  116. return self.clone(pow(value, self._value))
  117. def __floordiv__(self, value):
  118. return self.clone(self._value // value)
  119. def __rfloordiv__(self, value):
  120. return self.clone(value // self._value)
  121. if sys.version_info[0] <= 2:
  122. def __div__(self, value):
  123. if isinstance(value, float):
  124. return Real(self._value / value)
  125. else:
  126. return self.clone(self._value / value)
  127. def __rdiv__(self, value):
  128. if isinstance(value, float):
  129. return Real(value / self._value)
  130. else:
  131. return self.clone(value / self._value)
  132. else:
  133. def __truediv__(self, value):
  134. return Real(self._value / value)
  135. def __rtruediv__(self, value):
  136. return Real(value / self._value)
  137. def __divmod__(self, value):
  138. return self.clone(divmod(self._value, value))
  139. def __rdivmod__(self, value):
  140. return self.clone(divmod(value, self._value))
  141. __hash__ = base.AbstractSimpleAsn1Item.__hash__
  142. def __int__(self):
  143. return int(self._value)
  144. if sys.version_info[0] <= 2:
  145. def __long__(self):
  146. return long(self._value)
  147. def __float__(self):
  148. return float(self._value)
  149. def __abs__(self):
  150. return self.clone(abs(self._value))
  151. def __index__(self):
  152. return int(self._value)
  153. def __pos__(self):
  154. return self.clone(+self._value)
  155. def __neg__(self):
  156. return self.clone(-self._value)
  157. def __invert__(self):
  158. return self.clone(~self._value)
  159. def __round__(self, n=0):
  160. r = round(self._value, n)
  161. if n:
  162. return self.clone(r)
  163. else:
  164. return r
  165. def __floor__(self):
  166. return math.floor(self._value)
  167. def __ceil__(self):
  168. return math.ceil(self._value)
  169. if sys.version_info[0:2] > (2, 5):
  170. def __trunc__(self):
  171. return self.clone(math.trunc(self._value))
  172. def __lt__(self, value):
  173. return self._value < value
  174. def __le__(self, value):
  175. return self._value <= value
  176. def __eq__(self, value):
  177. return self._value == value
  178. def __ne__(self, value):
  179. return self._value != value
  180. def __gt__(self, value):
  181. return self._value > value
  182. def __ge__(self, value):
  183. return self._value >= value
  184. def prettyIn(self, value):
  185. try:
  186. return int(value)
  187. except ValueError:
  188. try:
  189. return self.namedValues[value]
  190. except KeyError:
  191. raise error.PyAsn1Error(
  192. 'Can\'t coerce %r into integer: %s' % (value, sys.exc_info()[1])
  193. )
  194. def prettyOut(self, value):
  195. try:
  196. return str(self.namedValues[value])
  197. except KeyError:
  198. return str(value)
  199. # backward compatibility
  200. def getNamedValues(self):
  201. return self.namedValues
  202. class Boolean(Integer):
  203. """Create |ASN.1| type or object.
  204. |ASN.1| objects are immutable and duck-type Python :class:`int` objects.
  205. Keyword Args
  206. ------------
  207. value: :class:`int`, :class:`str` or |ASN.1| object
  208. Python integer or boolean or string literal or |ASN.1| class instance.
  209. tagSet: :py:class:`~pyasn1.type.tag.TagSet`
  210. Object representing non-default ASN.1 tag(s)
  211. subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
  212. Object representing non-default ASN.1 subtype constraint(s)
  213. namedValues: :py:class:`~pyasn1.type.namedval.NamedValues`
  214. Object representing non-default symbolic aliases for numbers
  215. Raises
  216. ------
  217. :py:class:`~pyasn1.error.PyAsn1Error`
  218. On constraint violation or bad initializer.
  219. Examples
  220. --------
  221. .. code-block:: python
  222. class RoundResult(Boolean):
  223. '''
  224. ASN.1 specification:
  225. RoundResult ::= BOOLEAN
  226. ok RoundResult ::= TRUE
  227. ko RoundResult ::= FALSE
  228. '''
  229. ok = RoundResult(True)
  230. ko = RoundResult(False)
  231. """
  232. #: Set (on class, not on instance) or return a
  233. #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s)
  234. #: associated with |ASN.1| type.
  235. tagSet = tag.initTagSet(
  236. tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x01),
  237. )
  238. #: Set (on class, not on instance) or return a
  239. #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object
  240. #: imposing constraints on |ASN.1| type initialization values.
  241. subtypeSpec = Integer.subtypeSpec + constraint.SingleValueConstraint(0, 1)
  242. #: Default :py:class:`~pyasn1.type.namedval.NamedValues` object
  243. #: representing symbolic aliases for numbers
  244. namedValues = namedval.NamedValues(('False', 0), ('True', 1))
  245. # Optimization for faster codec lookup
  246. typeId = Integer.getTypeId()
  247. if sys.version_info[0] < 3:
  248. SizedIntegerBase = long
  249. else:
  250. SizedIntegerBase = int
  251. class SizedInteger(SizedIntegerBase):
  252. bitLength = leadingZeroBits = None
  253. def setBitLength(self, bitLength):
  254. self.bitLength = bitLength
  255. self.leadingZeroBits = max(bitLength - integer.bitLength(self), 0)
  256. return self
  257. def __len__(self):
  258. if self.bitLength is None:
  259. self.setBitLength(integer.bitLength(self))
  260. return self.bitLength
  261. class BitString(base.AbstractSimpleAsn1Item):
  262. """Create |ASN.1| schema or value object.
  263. |ASN.1| objects are immutable and duck-type both Python :class:`tuple` (as a tuple
  264. of bits) and :class:`int` objects.
  265. Keyword Args
  266. ------------
  267. value: :class:`int`, :class:`str` or |ASN.1| object
  268. Python integer or string literal representing binary or hexadecimal
  269. number or sequence of integer bits or |ASN.1| object.
  270. tagSet: :py:class:`~pyasn1.type.tag.TagSet`
  271. Object representing non-default ASN.1 tag(s)
  272. subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
  273. Object representing non-default ASN.1 subtype constraint(s)
  274. namedValues: :py:class:`~pyasn1.type.namedval.NamedValues`
  275. Object representing non-default symbolic aliases for numbers
  276. binValue: :py:class:`str`
  277. Binary string initializer to use instead of the *value*.
  278. Example: '10110011'.
  279. hexValue: :py:class:`str`
  280. Hexadecimal string initializer to use instead of the *value*.
  281. Example: 'DEADBEEF'.
  282. Raises
  283. ------
  284. :py:class:`~pyasn1.error.PyAsn1Error`
  285. On constraint violation or bad initializer.
  286. Examples
  287. --------
  288. .. code-block:: python
  289. class Rights(BitString):
  290. '''
  291. ASN.1 specification:
  292. Rights ::= BIT STRING { user-read(0), user-write(1),
  293. group-read(2), group-write(3),
  294. other-read(4), other-write(5) }
  295. group1 Rights ::= { group-read, group-write }
  296. group2 Rights ::= '0011'B
  297. group3 Rights ::= '3'H
  298. '''
  299. namedValues = NamedValues(
  300. ('user-read', 0), ('user-write', 1),
  301. ('group-read', 2), ('group-write', 3),
  302. ('other-read', 4), ('other-write', 5)
  303. )
  304. group1 = Rights(('group-read', 'group-write'))
  305. group2 = Rights('0011')
  306. group3 = Rights(0x3)
  307. """
  308. #: Set (on class, not on instance) or return a
  309. #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s)
  310. #: associated with |ASN.1| type.
  311. tagSet = tag.initTagSet(
  312. tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x03)
  313. )
  314. #: Set (on class, not on instance) or return a
  315. #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object
  316. #: imposing constraints on |ASN.1| type initialization values.
  317. subtypeSpec = constraint.ConstraintsIntersection()
  318. #: Default :py:class:`~pyasn1.type.namedval.NamedValues` object
  319. #: representing symbolic aliases for numbers
  320. namedValues = namedval.NamedValues()
  321. # Optimization for faster codec lookup
  322. typeId = base.AbstractSimpleAsn1Item.getTypeId()
  323. defaultBinValue = defaultHexValue = noValue
  324. def __init__(self, value=noValue, **kwargs):
  325. if value is noValue:
  326. if kwargs:
  327. try:
  328. value = self.fromBinaryString(kwargs.pop('binValue'), internalFormat=True)
  329. except KeyError:
  330. pass
  331. try:
  332. value = self.fromHexString(kwargs.pop('hexValue'), internalFormat=True)
  333. except KeyError:
  334. pass
  335. if value is noValue:
  336. if self.defaultBinValue is not noValue:
  337. value = self.fromBinaryString(self.defaultBinValue, internalFormat=True)
  338. elif self.defaultHexValue is not noValue:
  339. value = self.fromHexString(self.defaultHexValue, internalFormat=True)
  340. if 'namedValues' not in kwargs:
  341. kwargs['namedValues'] = self.namedValues
  342. base.AbstractSimpleAsn1Item.__init__(self, value, **kwargs)
  343. def __str__(self):
  344. return self.asBinary()
  345. def __eq__(self, other):
  346. other = self.prettyIn(other)
  347. return self is other or self._value == other and len(self._value) == len(other)
  348. def __ne__(self, other):
  349. other = self.prettyIn(other)
  350. return self._value != other or len(self._value) != len(other)
  351. def __lt__(self, other):
  352. other = self.prettyIn(other)
  353. return len(self._value) < len(other) or len(self._value) == len(other) and self._value < other
  354. def __le__(self, other):
  355. other = self.prettyIn(other)
  356. return len(self._value) <= len(other) or len(self._value) == len(other) and self._value <= other
  357. def __gt__(self, other):
  358. other = self.prettyIn(other)
  359. return len(self._value) > len(other) or len(self._value) == len(other) and self._value > other
  360. def __ge__(self, other):
  361. other = self.prettyIn(other)
  362. return len(self._value) >= len(other) or len(self._value) == len(other) and self._value >= other
  363. # Immutable sequence object protocol
  364. def __len__(self):
  365. return len(self._value)
  366. def __getitem__(self, i):
  367. if i.__class__ is slice:
  368. return self.clone([self[x] for x in range(*i.indices(len(self)))])
  369. else:
  370. length = len(self._value) - 1
  371. if i > length or i < 0:
  372. raise IndexError('bit index out of range')
  373. return (self._value >> (length - i)) & 1
  374. def __iter__(self):
  375. length = len(self._value)
  376. while length:
  377. length -= 1
  378. yield (self._value >> length) & 1
  379. def __reversed__(self):
  380. return reversed(tuple(self))
  381. # arithmetic operators
  382. def __add__(self, value):
  383. value = self.prettyIn(value)
  384. return self.clone(SizedInteger(self._value << len(value) | value).setBitLength(len(self._value) + len(value)))
  385. def __radd__(self, value):
  386. value = self.prettyIn(value)
  387. return self.clone(SizedInteger(value << len(self._value) | self._value).setBitLength(len(self._value) + len(value)))
  388. def __mul__(self, value):
  389. bitString = self._value
  390. while value > 1:
  391. bitString <<= len(self._value)
  392. bitString |= self._value
  393. value -= 1
  394. return self.clone(bitString)
  395. def __rmul__(self, value):
  396. return self * value
  397. def __lshift__(self, count):
  398. return self.clone(SizedInteger(self._value << count).setBitLength(len(self._value) + count))
  399. def __rshift__(self, count):
  400. return self.clone(SizedInteger(self._value >> count).setBitLength(max(0, len(self._value) - count)))
  401. def __int__(self):
  402. return self._value
  403. def __float__(self):
  404. return float(self._value)
  405. if sys.version_info[0] < 3:
  406. def __long__(self):
  407. return self._value
  408. def asNumbers(self):
  409. """Get |ASN.1| value as a sequence of 8-bit integers.
  410. If |ASN.1| object length is not a multiple of 8, result
  411. will be left-padded with zeros.
  412. """
  413. return tuple(octets.octs2ints(self.asOctets()))
  414. def asOctets(self):
  415. """Get |ASN.1| value as a sequence of octets.
  416. If |ASN.1| object length is not a multiple of 8, result
  417. will be left-padded with zeros.
  418. """
  419. return integer.to_bytes(self._value, length=len(self))
  420. def asInteger(self):
  421. """Get |ASN.1| value as a single integer value.
  422. """
  423. return self._value
  424. def asBinary(self):
  425. """Get |ASN.1| value as a text string of bits.
  426. """
  427. binString = binary.bin(self._value)[2:]
  428. return '0' * (len(self._value) - len(binString)) + binString
  429. @classmethod
  430. def fromHexString(cls, value, internalFormat=False, prepend=None):
  431. """Create a |ASN.1| object initialized from the hex string.
  432. Parameters
  433. ----------
  434. value: :class:`str`
  435. Text string like 'DEADBEEF'
  436. """
  437. try:
  438. value = SizedInteger(value, 16).setBitLength(len(value) * 4)
  439. except ValueError:
  440. raise error.PyAsn1Error('%s.fromHexString() error: %s' % (cls.__name__, sys.exc_info()[1]))
  441. if prepend is not None:
  442. value = SizedInteger(
  443. (SizedInteger(prepend) << len(value)) | value
  444. ).setBitLength(len(prepend) + len(value))
  445. if not internalFormat:
  446. value = cls(value)
  447. return value
  448. @classmethod
  449. def fromBinaryString(cls, value, internalFormat=False, prepend=None):
  450. """Create a |ASN.1| object initialized from a string of '0' and '1'.
  451. Parameters
  452. ----------
  453. value: :class:`str`
  454. Text string like '1010111'
  455. """
  456. try:
  457. value = SizedInteger(value or '0', 2).setBitLength(len(value))
  458. except ValueError:
  459. raise error.PyAsn1Error('%s.fromBinaryString() error: %s' % (cls.__name__, sys.exc_info()[1]))
  460. if prepend is not None:
  461. value = SizedInteger(
  462. (SizedInteger(prepend) << len(value)) | value
  463. ).setBitLength(len(prepend) + len(value))
  464. if not internalFormat:
  465. value = cls(value)
  466. return value
  467. @classmethod
  468. def fromOctetString(cls, value, internalFormat=False, prepend=None, padding=0):
  469. """Create a |ASN.1| object initialized from a string.
  470. Parameters
  471. ----------
  472. value: :class:`str` (Py2) or :class:`bytes` (Py3)
  473. Text string like '\\\\x01\\\\xff' (Py2) or b'\\\\x01\\\\xff' (Py3)
  474. """
  475. value = SizedInteger(integer.from_bytes(value) >> padding).setBitLength(len(value) * 8 - padding)
  476. if prepend is not None:
  477. value = SizedInteger(
  478. (SizedInteger(prepend) << len(value)) | value
  479. ).setBitLength(len(prepend) + len(value))
  480. if not internalFormat:
  481. value = cls(value)
  482. return value
  483. def prettyIn(self, value):
  484. if isinstance(value, SizedInteger):
  485. return value
  486. elif octets.isStringType(value):
  487. if not value:
  488. return SizedInteger(0).setBitLength(0)
  489. elif value[0] == '\'': # "'1011'B" -- ASN.1 schema representation (deprecated)
  490. if value[-2:] == '\'B':
  491. return self.fromBinaryString(value[1:-2], internalFormat=True)
  492. elif value[-2:] == '\'H':
  493. return self.fromHexString(value[1:-2], internalFormat=True)
  494. else:
  495. raise error.PyAsn1Error(
  496. 'Bad BIT STRING value notation %s' % (value,)
  497. )
  498. elif self.namedValues and not value.isdigit(): # named bits like 'Urgent, Active'
  499. names = [x.strip() for x in value.split(',')]
  500. try:
  501. bitPositions = [self.namedValues[name] for name in names]
  502. except KeyError:
  503. raise error.PyAsn1Error('unknown bit name(s) in %r' % (names,))
  504. rightmostPosition = max(bitPositions)
  505. number = 0
  506. for bitPosition in bitPositions:
  507. number |= 1 << (rightmostPosition - bitPosition)
  508. return SizedInteger(number).setBitLength(rightmostPosition + 1)
  509. elif value.startswith('0x'):
  510. return self.fromHexString(value[2:], internalFormat=True)
  511. elif value.startswith('0b'):
  512. return self.fromBinaryString(value[2:], internalFormat=True)
  513. else: # assume plain binary string like '1011'
  514. return self.fromBinaryString(value, internalFormat=True)
  515. elif isinstance(value, (tuple, list)):
  516. return self.fromBinaryString(''.join([b and '1' or '0' for b in value]), internalFormat=True)
  517. elif isinstance(value, BitString):
  518. return SizedInteger(value).setBitLength(len(value))
  519. elif isinstance(value, intTypes):
  520. return SizedInteger(value)
  521. else:
  522. raise error.PyAsn1Error(
  523. 'Bad BitString initializer type \'%s\'' % (value,)
  524. )
  525. try:
  526. # noinspection PyStatementEffect
  527. all
  528. except NameError: # Python 2.4
  529. # noinspection PyShadowingBuiltins
  530. def all(iterable):
  531. for element in iterable:
  532. if not element:
  533. return False
  534. return True
  535. class OctetString(base.AbstractSimpleAsn1Item):
  536. """Create |ASN.1| schema or value object.
  537. |ASN.1| objects are immutable and duck-type Python 2 :class:`str` or Python 3 :class:`bytes`.
  538. When used in Unicode context, |ASN.1| type assumes "|encoding|" serialisation.
  539. Keyword Args
  540. ------------
  541. value: :class:`str`, :class:`bytes` or |ASN.1| object
  542. string (Python 2) or bytes (Python 3), alternatively unicode object
  543. (Python 2) or string (Python 3) representing character string to be
  544. serialised into octets (note `encoding` parameter) or |ASN.1| object.
  545. tagSet: :py:class:`~pyasn1.type.tag.TagSet`
  546. Object representing non-default ASN.1 tag(s)
  547. subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
  548. Object representing non-default ASN.1 subtype constraint(s)
  549. encoding: :py:class:`str`
  550. Unicode codec ID to encode/decode :class:`unicode` (Python 2) or
  551. :class:`str` (Python 3) the payload when |ASN.1| object is used
  552. in text string context.
  553. binValue: :py:class:`str`
  554. Binary string initializer to use instead of the *value*.
  555. Example: '10110011'.
  556. hexValue: :py:class:`str`
  557. Hexadecimal string initializer to use instead of the *value*.
  558. Example: 'DEADBEEF'.
  559. Raises
  560. ------
  561. :py:class:`~pyasn1.error.PyAsn1Error`
  562. On constraint violation or bad initializer.
  563. Examples
  564. --------
  565. .. code-block:: python
  566. class Icon(OctetString):
  567. '''
  568. ASN.1 specification:
  569. Icon ::= OCTET STRING
  570. icon1 Icon ::= '001100010011001000110011'B
  571. icon2 Icon ::= '313233'H
  572. '''
  573. icon1 = Icon.fromBinaryString('001100010011001000110011')
  574. icon2 = Icon.fromHexString('313233')
  575. """
  576. #: Set (on class, not on instance) or return a
  577. #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s)
  578. #: associated with |ASN.1| type.
  579. tagSet = tag.initTagSet(
  580. tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x04)
  581. )
  582. #: Set (on class, not on instance) or return a
  583. #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object
  584. #: imposing constraints on |ASN.1| type initialization values.
  585. subtypeSpec = constraint.ConstraintsIntersection()
  586. # Optimization for faster codec lookup
  587. typeId = base.AbstractSimpleAsn1Item.getTypeId()
  588. defaultBinValue = defaultHexValue = noValue
  589. encoding = 'iso-8859-1'
  590. def __init__(self, value=noValue, **kwargs):
  591. if kwargs:
  592. if value is noValue:
  593. try:
  594. value = self.fromBinaryString(kwargs.pop('binValue'))
  595. except KeyError:
  596. pass
  597. try:
  598. value = self.fromHexString(kwargs.pop('hexValue'))
  599. except KeyError:
  600. pass
  601. if value is noValue:
  602. if self.defaultBinValue is not noValue:
  603. value = self.fromBinaryString(self.defaultBinValue)
  604. elif self.defaultHexValue is not noValue:
  605. value = self.fromHexString(self.defaultHexValue)
  606. if 'encoding' not in kwargs:
  607. kwargs['encoding'] = self.encoding
  608. base.AbstractSimpleAsn1Item.__init__(self, value, **kwargs)
  609. if sys.version_info[0] <= 2:
  610. def prettyIn(self, value):
  611. if isinstance(value, str):
  612. return value
  613. elif isinstance(value, unicode):
  614. try:
  615. return value.encode(self.encoding)
  616. except (LookupError, UnicodeEncodeError):
  617. raise error.PyAsn1Error(
  618. "Can't encode string '%s' with codec %s" % (value, self.encoding)
  619. )
  620. elif isinstance(value, (tuple, list)):
  621. try:
  622. return ''.join([chr(x) for x in value])
  623. except ValueError:
  624. raise error.PyAsn1Error(
  625. "Bad %s initializer '%s'" % (self.__class__.__name__, value)
  626. )
  627. else:
  628. return str(value)
  629. def __str__(self):
  630. return str(self._value)
  631. def __unicode__(self):
  632. try:
  633. return self._value.decode(self.encoding)
  634. except UnicodeDecodeError:
  635. raise error.PyAsn1Error(
  636. "Can't decode string '%s' with codec %s" % (self._value, self.encoding)
  637. )
  638. def asOctets(self):
  639. return str(self._value)
  640. def asNumbers(self):
  641. return tuple([ord(x) for x in self._value])
  642. else:
  643. def prettyIn(self, value):
  644. if isinstance(value, bytes):
  645. return value
  646. elif isinstance(value, str):
  647. try:
  648. return value.encode(self.encoding)
  649. except UnicodeEncodeError:
  650. raise error.PyAsn1Error(
  651. "Can't encode string '%s' with '%s' codec" % (value, self.encoding)
  652. )
  653. elif isinstance(value, OctetString): # a shortcut, bytes() would work the same way
  654. return value.asOctets()
  655. elif isinstance(value, base.AbstractSimpleAsn1Item): # this mostly targets Integer objects
  656. return self.prettyIn(str(value))
  657. elif isinstance(value, (tuple, list)):
  658. return self.prettyIn(bytes(value))
  659. else:
  660. return bytes(value)
  661. def __str__(self):
  662. try:
  663. return self._value.decode(self.encoding)
  664. except UnicodeDecodeError:
  665. raise error.PyAsn1Error(
  666. "Can't decode string '%s' with '%s' codec at '%s'" % (self._value, self.encoding, self.__class__.__name__)
  667. )
  668. def __bytes__(self):
  669. return bytes(self._value)
  670. def asOctets(self):
  671. return bytes(self._value)
  672. def asNumbers(self):
  673. return tuple(self._value)
  674. #
  675. # Normally, `.prettyPrint()` is called from `__str__()`. Historically,
  676. # OctetString.prettyPrint() used to return hexified payload
  677. # representation in cases when non-printable content is present. At the
  678. # same time `str()` used to produce either octet-stream (Py2) or
  679. # text (Py3) representations.
  680. #
  681. # Therefore `OctetString.__str__()` -> `.prettyPrint()` call chain is
  682. # reversed to preserve the original behaviour.
  683. #
  684. # Eventually we should deprecate `.prettyPrint()` / `.prettyOut()` harness
  685. # and end up with just `__str__()` producing hexified representation while
  686. # both text and octet-stream representation should only be requested via
  687. # the `.asOctets()` method.
  688. #
  689. # Note: ASN.1 OCTET STRING is never mean to contain text!
  690. #
  691. def prettyOut(self, value):
  692. return value
  693. def prettyPrint(self, scope=0):
  694. # first see if subclass has its own .prettyOut()
  695. value = self.prettyOut(self._value)
  696. if value is not self._value:
  697. return value
  698. numbers = self.asNumbers()
  699. for x in numbers:
  700. # hexify if needed
  701. if x < 32 or x > 126:
  702. return '0x' + ''.join(('%.2x' % x for x in numbers))
  703. else:
  704. # this prevents infinite recursion
  705. return OctetString.__str__(self)
  706. @staticmethod
  707. def fromBinaryString(value):
  708. """Create a |ASN.1| object initialized from a string of '0' and '1'.
  709. Parameters
  710. ----------
  711. value: :class:`str`
  712. Text string like '1010111'
  713. """
  714. bitNo = 8
  715. byte = 0
  716. r = []
  717. for v in value:
  718. if bitNo:
  719. bitNo -= 1
  720. else:
  721. bitNo = 7
  722. r.append(byte)
  723. byte = 0
  724. if v in ('0', '1'):
  725. v = int(v)
  726. else:
  727. raise error.PyAsn1Error(
  728. 'Non-binary OCTET STRING initializer %s' % (v,)
  729. )
  730. byte |= v << bitNo
  731. r.append(byte)
  732. return octets.ints2octs(r)
  733. @staticmethod
  734. def fromHexString(value):
  735. """Create a |ASN.1| object initialized from the hex string.
  736. Parameters
  737. ----------
  738. value: :class:`str`
  739. Text string like 'DEADBEEF'
  740. """
  741. r = []
  742. p = []
  743. for v in value:
  744. if p:
  745. r.append(int(p + v, 16))
  746. p = None
  747. else:
  748. p = v
  749. if p:
  750. r.append(int(p + '0', 16))
  751. return octets.ints2octs(r)
  752. # Immutable sequence object protocol
  753. def __len__(self):
  754. return len(self._value)
  755. def __getitem__(self, i):
  756. if i.__class__ is slice:
  757. return self.clone(self._value[i])
  758. else:
  759. return self._value[i]
  760. def __iter__(self):
  761. return iter(self._value)
  762. def __contains__(self, value):
  763. return value in self._value
  764. def __add__(self, value):
  765. return self.clone(self._value + self.prettyIn(value))
  766. def __radd__(self, value):
  767. return self.clone(self.prettyIn(value) + self._value)
  768. def __mul__(self, value):
  769. return self.clone(self._value * value)
  770. def __rmul__(self, value):
  771. return self * value
  772. def __int__(self):
  773. return int(self._value)
  774. def __float__(self):
  775. return float(self._value)
  776. def __reversed__(self):
  777. return reversed(self._value)
  778. class Null(OctetString):
  779. """Create |ASN.1| schema or value object.
  780. |ASN.1| objects are immutable and duck-type Python :class:`str` objects (always empty).
  781. Keyword Args
  782. ------------
  783. value: :class:`str` or :py:class:`~pyasn1.type.univ.Null` object
  784. Python empty string literal or any object that evaluates to `False`
  785. tagSet: :py:class:`~pyasn1.type.tag.TagSet`
  786. Object representing non-default ASN.1 tag(s)
  787. Raises
  788. ------
  789. :py:class:`~pyasn1.error.PyAsn1Error`
  790. On constraint violation or bad initializer.
  791. Examples
  792. --------
  793. .. code-block:: python
  794. class Ack(Null):
  795. '''
  796. ASN.1 specification:
  797. Ack ::= NULL
  798. '''
  799. ack = Ack('')
  800. """
  801. #: Set (on class, not on instance) or return a
  802. #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s)
  803. #: associated with |ASN.1| type.
  804. tagSet = tag.initTagSet(
  805. tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x05)
  806. )
  807. subtypeSpec = OctetString.subtypeSpec + constraint.SingleValueConstraint(octets.str2octs(''))
  808. # Optimization for faster codec lookup
  809. typeId = OctetString.getTypeId()
  810. def prettyIn(self, value):
  811. if value:
  812. return value
  813. return octets.str2octs('')
  814. if sys.version_info[0] <= 2:
  815. intTypes = (int, long)
  816. else:
  817. intTypes = (int,)
  818. numericTypes = intTypes + (float,)
  819. class ObjectIdentifier(base.AbstractSimpleAsn1Item):
  820. """Create |ASN.1| schema or value object.
  821. |ASN.1| objects are immutable and duck-type Python :class:`tuple` objects (tuple of non-negative integers).
  822. Keyword Args
  823. ------------
  824. value: :class:`tuple`, :class:`str` or |ASN.1| object
  825. Python sequence of :class:`int` or string literal or |ASN.1| object.
  826. tagSet: :py:class:`~pyasn1.type.tag.TagSet`
  827. Object representing non-default ASN.1 tag(s)
  828. subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
  829. Object representing non-default ASN.1 subtype constraint(s)
  830. Raises
  831. ------
  832. :py:class:`~pyasn1.error.PyAsn1Error`
  833. On constraint violation or bad initializer.
  834. Examples
  835. --------
  836. .. code-block:: python
  837. class ID(ObjectIdentifier):
  838. '''
  839. ASN.1 specification:
  840. ID ::= OBJECT IDENTIFIER
  841. id-edims ID ::= { joint-iso-itu-t mhs-motif(6) edims(7) }
  842. id-bp ID ::= { id-edims 11 }
  843. '''
  844. id_edims = ID('2.6.7')
  845. id_bp = id_edims + (11,)
  846. """
  847. #: Set (on class, not on instance) or return a
  848. #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s)
  849. #: associated with |ASN.1| type.
  850. tagSet = tag.initTagSet(
  851. tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x06)
  852. )
  853. #: Set (on class, not on instance) or return a
  854. #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object
  855. #: imposing constraints on |ASN.1| type initialization values.
  856. subtypeSpec = constraint.ConstraintsIntersection()
  857. # Optimization for faster codec lookup
  858. typeId = base.AbstractSimpleAsn1Item.getTypeId()
  859. def __add__(self, other):
  860. return self.clone(self._value + other)
  861. def __radd__(self, other):
  862. return self.clone(other + self._value)
  863. def asTuple(self):
  864. return self._value
  865. # Sequence object protocol
  866. def __len__(self):
  867. return len(self._value)
  868. def __getitem__(self, i):
  869. if i.__class__ is slice:
  870. return self.clone(self._value[i])
  871. else:
  872. return self._value[i]
  873. def __iter__(self):
  874. return iter(self._value)
  875. def __contains__(self, value):
  876. return value in self._value
  877. def index(self, suboid):
  878. return self._value.index(suboid)
  879. def isPrefixOf(self, other):
  880. """Indicate if this |ASN.1| object is a prefix of other |ASN.1| object.
  881. Parameters
  882. ----------
  883. other: |ASN.1| object
  884. |ASN.1| object
  885. Returns
  886. -------
  887. : :class:`bool`
  888. :class:`True` if this |ASN.1| object is a parent (e.g. prefix) of the other |ASN.1| object
  889. or :class:`False` otherwise.
  890. """
  891. l = len(self)
  892. if l <= len(other):
  893. if self._value[:l] == other[:l]:
  894. return True
  895. return False
  896. def prettyIn(self, value):
  897. if isinstance(value, ObjectIdentifier):
  898. return tuple(value)
  899. elif octets.isStringType(value):
  900. if '-' in value:
  901. raise error.PyAsn1Error(
  902. 'Malformed Object ID %s at %s: %s' % (value, self.__class__.__name__, sys.exc_info()[1])
  903. )
  904. try:
  905. return tuple([int(subOid) for subOid in value.split('.') if subOid])
  906. except ValueError:
  907. raise error.PyAsn1Error(
  908. 'Malformed Object ID %s at %s: %s' % (value, self.__class__.__name__, sys.exc_info()[1])
  909. )
  910. try:
  911. tupleOfInts = tuple([int(subOid) for subOid in value if subOid >= 0])
  912. except (ValueError, TypeError):
  913. raise error.PyAsn1Error(
  914. 'Malformed Object ID %s at %s: %s' % (value, self.__class__.__name__, sys.exc_info()[1])
  915. )
  916. if len(tupleOfInts) == len(value):
  917. return tupleOfInts
  918. raise error.PyAsn1Error('Malformed Object ID %s at %s' % (value, self.__class__.__name__))
  919. def prettyOut(self, value):
  920. return '.'.join([str(x) for x in value])
  921. class Real(base.AbstractSimpleAsn1Item):
  922. """Create |ASN.1| schema or value object.
  923. |ASN.1| objects are immutable and duck-type Python :class:`float` objects.
  924. Additionally, |ASN.1| objects behave like a :class:`tuple` in which case its
  925. elements are mantissa, base and exponent.
  926. Keyword Args
  927. ------------
  928. value: :class:`tuple`, :class:`float` or |ASN.1| object
  929. Python sequence of :class:`int` (representing mantissa, base and
  930. exponent) or float instance or *Real* class instance.
  931. tagSet: :py:class:`~pyasn1.type.tag.TagSet`
  932. Object representing non-default ASN.1 tag(s)
  933. subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
  934. Object representing non-default ASN.1 subtype constraint(s)
  935. Raises
  936. ------
  937. :py:class:`~pyasn1.error.PyAsn1Error`
  938. On constraint violation or bad initializer.
  939. Examples
  940. --------
  941. .. code-block:: python
  942. class Pi(Real):
  943. '''
  944. ASN.1 specification:
  945. Pi ::= REAL
  946. pi Pi ::= { mantissa 314159, base 10, exponent -5 }
  947. '''
  948. pi = Pi((314159, 10, -5))
  949. """
  950. binEncBase = None # binEncBase = 16 is recommended for large numbers
  951. try:
  952. _plusInf = float('inf')
  953. _minusInf = float('-inf')
  954. _inf = _plusInf, _minusInf
  955. except ValueError:
  956. # Infinity support is platform and Python dependent
  957. _plusInf = _minusInf = None
  958. _inf = ()
  959. #: Set (on class, not on instance) or return a
  960. #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s)
  961. #: associated with |ASN.1| type.
  962. tagSet = tag.initTagSet(
  963. tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x09)
  964. )
  965. #: Set (on class, not on instance) or return a
  966. #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object
  967. #: imposing constraints on |ASN.1| type initialization values.
  968. subtypeSpec = constraint.ConstraintsIntersection()
  969. # Optimization for faster codec lookup
  970. typeId = base.AbstractSimpleAsn1Item.getTypeId()
  971. @staticmethod
  972. def __normalizeBase10(value):
  973. m, b, e = value
  974. while m and m % 10 == 0:
  975. m /= 10
  976. e += 1
  977. return m, b, e
  978. def prettyIn(self, value):
  979. if isinstance(value, tuple) and len(value) == 3:
  980. if (not isinstance(value[0], numericTypes) or
  981. not isinstance(value[1], intTypes) or
  982. not isinstance(value[2], intTypes)):
  983. raise error.PyAsn1Error('Lame Real value syntax: %s' % (value,))
  984. if (isinstance(value[0], float) and
  985. self._inf and value[0] in self._inf):
  986. return value[0]
  987. if value[1] not in (2, 10):
  988. raise error.PyAsn1Error(
  989. 'Prohibited base for Real value: %s' % (value[1],)
  990. )
  991. if value[1] == 10:
  992. value = self.__normalizeBase10(value)
  993. return value
  994. elif isinstance(value, intTypes):
  995. return self.__normalizeBase10((value, 10, 0))
  996. elif isinstance(value, float) or octets.isStringType(value):
  997. if octets.isStringType(value):
  998. try:
  999. value = float(value)
  1000. except ValueError:
  1001. raise error.PyAsn1Error(
  1002. 'Bad real value syntax: %s' % (value,)
  1003. )
  1004. if self._inf and value in self._inf:
  1005. return value
  1006. else:
  1007. e = 0
  1008. while int(value) != value:
  1009. value *= 10
  1010. e -= 1
  1011. return self.__normalizeBase10((int(value), 10, e))
  1012. elif isinstance(value, Real):
  1013. return tuple(value)
  1014. raise error.PyAsn1Error(
  1015. 'Bad real value syntax: %s' % (value,)
  1016. )
  1017. def prettyPrint(self, scope=0):
  1018. try:
  1019. return self.prettyOut(float(self))
  1020. except OverflowError:
  1021. return '<overflow>'
  1022. @property
  1023. def isPlusInf(self):
  1024. """Indicate PLUS-INFINITY object value
  1025. Returns
  1026. -------
  1027. : :class:`bool`
  1028. :class:`True` if calling object represents plus infinity
  1029. or :class:`False` otherwise.
  1030. """
  1031. return self._value == self._plusInf
  1032. @property
  1033. def isMinusInf(self):
  1034. """Indicate MINUS-INFINITY object value
  1035. Returns
  1036. -------
  1037. : :class:`bool`
  1038. :class:`True` if calling object represents minus infinity
  1039. or :class:`False` otherwise.
  1040. """
  1041. return self._value == self._minusInf
  1042. @property
  1043. def isInf(self):
  1044. return self._value in self._inf
  1045. def __add__(self, value):
  1046. return self.clone(float(self) + value)
  1047. def __radd__(self, value):
  1048. return self + value
  1049. def __mul__(self, value):
  1050. return self.clone(float(self) * value)
  1051. def __rmul__(self, value):
  1052. return self * value
  1053. def __sub__(self, value):
  1054. return self.clone(float(self) - value)
  1055. def __rsub__(self, value):
  1056. return self.clone(value - float(self))
  1057. def __mod__(self, value):
  1058. return self.clone(float(self) % value)
  1059. def __rmod__(self, value):
  1060. return self.clone(value % float(self))
  1061. def __pow__(self, value, modulo=None):
  1062. return self.clone(pow(float(self), value, modulo))
  1063. def __rpow__(self, value):
  1064. return self.clone(pow(value, float(self)))
  1065. if sys.version_info[0] <= 2:
  1066. def __div__(self, value):
  1067. return self.clone(float(self) / value)
  1068. def __rdiv__(self, value):
  1069. return self.clone(value / float(self))
  1070. else:
  1071. def __truediv__(self, value):
  1072. return self.clone(float(self) / value)
  1073. def __rtruediv__(self, value):
  1074. return self.clone(value / float(self))
  1075. def __divmod__(self, value):
  1076. return self.clone(float(self) // value)
  1077. def __rdivmod__(self, value):
  1078. return self.clone(value // float(self))
  1079. def __int__(self):
  1080. return int(float(self))
  1081. if sys.version_info[0] <= 2:
  1082. def __long__(self):
  1083. return long(float(self))
  1084. def __float__(self):
  1085. if self._value in self._inf:
  1086. return self._value
  1087. else:
  1088. return float(
  1089. self._value[0] * pow(self._value[1], self._value[2])
  1090. )
  1091. def __abs__(self):
  1092. return self.clone(abs(float(self)))
  1093. def __pos__(self):
  1094. return self.clone(+float(self))
  1095. def __neg__(self):
  1096. return self.clone(-float(self))
  1097. def __round__(self, n=0):
  1098. r = round(float(self), n)
  1099. if n:
  1100. return self.clone(r)
  1101. else:
  1102. return r
  1103. def __floor__(self):
  1104. return self.clone(math.floor(float(self)))
  1105. def __ceil__(self):
  1106. return self.clone(math.ceil(float(self)))
  1107. if sys.version_info[0:2] > (2, 5):
  1108. def __trunc__(self):
  1109. return self.clone(math.trunc(float(self)))
  1110. def __lt__(self, value):
  1111. return float(self) < value
  1112. def __le__(self, value):
  1113. return float(self) <= value
  1114. def __eq__(self, value):
  1115. return float(self) == value
  1116. def __ne__(self, value):
  1117. return float(self) != value
  1118. def __gt__(self, value):
  1119. return float(self) > value
  1120. def __ge__(self, value):
  1121. return float(self) >= value
  1122. if sys.version_info[0] <= 2:
  1123. def __nonzero__(self):
  1124. return bool(float(self))
  1125. else:
  1126. def __bool__(self):
  1127. return bool(float(self))
  1128. __hash__ = base.AbstractSimpleAsn1Item.__hash__
  1129. def __getitem__(self, idx):
  1130. if self._value in self._inf:
  1131. raise error.PyAsn1Error('Invalid infinite value operation')
  1132. else:
  1133. return self._value[idx]
  1134. # compatibility stubs
  1135. def isPlusInfinity(self):
  1136. return self.isPlusInf
  1137. def isMinusInfinity(self):
  1138. return self.isMinusInf
  1139. def isInfinity(self):
  1140. return self.isInf
  1141. class Enumerated(Integer):
  1142. """Create |ASN.1| type or object.
  1143. |ASN.1| objects are immutable and duck-type Python :class:`int` objects.
  1144. Keyword Args
  1145. ------------
  1146. value: :class:`int`, :class:`str` or |ASN.1| object
  1147. Python integer or string literal or |ASN.1| class instance.
  1148. tagSet: :py:class:`~pyasn1.type.tag.TagSet`
  1149. Object representing non-default ASN.1 tag(s)
  1150. subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
  1151. Object representing non-default ASN.1 subtype constraint(s)
  1152. namedValues: :py:class:`~pyasn1.type.namedval.NamedValues`
  1153. Object representing non-default symbolic aliases for numbers
  1154. Raises
  1155. ------
  1156. :py:class:`~pyasn1.error.PyAsn1Error`
  1157. On constraint violation or bad initializer.
  1158. Examples
  1159. --------
  1160. .. code-block:: python
  1161. class RadioButton(Enumerated):
  1162. '''
  1163. ASN.1 specification:
  1164. RadioButton ::= ENUMERATED { button1(0), button2(1),
  1165. button3(2) }
  1166. selected-by-default RadioButton ::= button1
  1167. '''
  1168. namedValues = NamedValues(
  1169. ('button1', 0), ('button2', 1),
  1170. ('button3', 2)
  1171. )
  1172. selected_by_default = RadioButton('button1')
  1173. """
  1174. #: Set (on class, not on instance) or return a
  1175. #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s)
  1176. #: associated with |ASN.1| type.
  1177. tagSet = tag.initTagSet(
  1178. tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x0A)
  1179. )
  1180. #: Set (on class, not on instance) or return a
  1181. #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object
  1182. #: imposing constraints on |ASN.1| type initialization values.
  1183. subtypeSpec = constraint.ConstraintsIntersection()
  1184. # Optimization for faster codec lookup
  1185. typeId = Integer.getTypeId()
  1186. #: Default :py:class:`~pyasn1.type.namedval.NamedValues` object
  1187. #: representing symbolic aliases for numbers
  1188. namedValues = namedval.NamedValues()
  1189. # "Structured" ASN.1 types
  1190. class SequenceOfAndSetOfBase(base.AbstractConstructedAsn1Item):
  1191. """Create |ASN.1| type.
  1192. |ASN.1| objects are mutable and duck-type Python :class:`list` objects.
  1193. Keyword Args
  1194. ------------
  1195. componentType : :py:class:`~pyasn1.type.base.PyAsn1Item` derivative
  1196. A pyasn1 object representing ASN.1 type allowed within |ASN.1| type
  1197. tagSet: :py:class:`~pyasn1.type.tag.TagSet`
  1198. Object representing non-default ASN.1 tag(s)
  1199. subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
  1200. Object representing non-default ASN.1 subtype constraint(s)
  1201. sizeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
  1202. Object representing collection size constraint
  1203. Examples
  1204. --------
  1205. .. code-block:: python
  1206. class LotteryDraw(SequenceOf): # SetOf is similar
  1207. '''
  1208. ASN.1 specification:
  1209. LotteryDraw ::= SEQUENCE OF INTEGER
  1210. '''
  1211. componentType = Integer()
  1212. lotteryDraw = LotteryDraw()
  1213. lotteryDraw.extend([123, 456, 789])
  1214. """
  1215. def __init__(self, *args, **kwargs):
  1216. # support positional params for backward compatibility
  1217. if args:
  1218. for key, value in zip(('componentType', 'tagSet',
  1219. 'subtypeSpec', 'sizeSpec'), args):
  1220. if key in kwargs:
  1221. raise error.PyAsn1Error('Conflicting positional and keyword params!')
  1222. kwargs['componentType'] = value
  1223. base.AbstractConstructedAsn1Item.__init__(self, **kwargs)
  1224. # Python list protocol
  1225. def __getitem__(self, idx):
  1226. try:
  1227. return self.getComponentByPosition(idx)
  1228. except error.PyAsn1Error:
  1229. raise IndexError(sys.exc_info()[1])
  1230. def __setitem__(self, idx, value):
  1231. try:
  1232. self.setComponentByPosition(idx, value)
  1233. except error.PyAsn1Error:
  1234. raise IndexError(sys.exc_info()[1])
  1235. def clear(self):
  1236. self._componentValues = []
  1237. def append(self, value):
  1238. self[len(self)] = value
  1239. def count(self, value):
  1240. return self._componentValues.count(value)
  1241. def extend(self, values):
  1242. for value in values:
  1243. self.append(value)
  1244. def index(self, value, start=0, stop=None):
  1245. if stop is None:
  1246. stop = len(self)
  1247. try:
  1248. return self._componentValues.index(value, start, stop)
  1249. except error.PyAsn1Error:
  1250. raise ValueError(sys.exc_info()[1])
  1251. def reverse(self):
  1252. self._componentValues.reverse()
  1253. def sort(self, key=None, reverse=False):
  1254. self._componentValues.sort(key=key, reverse=reverse)
  1255. def __iter__(self):
  1256. return iter(self._componentValues)
  1257. def _cloneComponentValues(self, myClone, cloneValueFlag):
  1258. for idx, componentValue in enumerate(self._componentValues):
  1259. if componentValue is not noValue:
  1260. if isinstance(componentValue, base.AbstractConstructedAsn1Item):
  1261. myClone.setComponentByPosition(
  1262. idx, componentValue.clone(cloneValueFlag=cloneValueFlag)
  1263. )
  1264. else:
  1265. myClone.setComponentByPosition(idx, componentValue.clone())
  1266. def getComponentByPosition(self, idx, default=noValue, instantiate=True):
  1267. """Return |ASN.1| type component value by position.
  1268. Equivalent to Python sequence subscription operation (e.g. `[]`).
  1269. Parameters
  1270. ----------
  1271. idx : :class:`int`
  1272. Component index (zero-based). Must either refer to an existing
  1273. component or to N+1 component (if *componentType* is set). In the latter
  1274. case a new component type gets instantiated and appended to the |ASN.1|
  1275. sequence.
  1276. Keyword Args
  1277. ------------
  1278. default: :class:`object`
  1279. If set and requested component is a schema object, return the `default`
  1280. object instead of the requested component.
  1281. instantiate: :class:`bool`
  1282. If `True` (default), inner component will be automatically instantiated.
  1283. If 'False' either existing component or the `noValue` object will be
  1284. returned.
  1285. Returns
  1286. -------
  1287. : :py:class:`~pyasn1.type.base.PyAsn1Item`
  1288. Instantiate |ASN.1| component type or return existing component value
  1289. Examples
  1290. --------
  1291. .. code-block:: python
  1292. # can also be SetOf
  1293. class MySequenceOf(SequenceOf):
  1294. componentType = OctetString()
  1295. s = MySequenceOf()
  1296. # returns component #0 with `.isValue` property False
  1297. s.getComponentByPosition(0)
  1298. # returns None
  1299. s.getComponentByPosition(0, default=None)
  1300. s.clear()
  1301. # returns noValue
  1302. s.getComponentByPosition(0, instantiate=False)
  1303. # sets component #0 to OctetString() ASN.1 schema
  1304. # object and returns it
  1305. s.getComponentByPosition(0, instantiate=True)
  1306. # sets component #0 to ASN.1 value object
  1307. s.setComponentByPosition(0, 'ABCD')
  1308. # returns OctetString('ABCD') value object
  1309. s.getComponentByPosition(0, instantiate=False)
  1310. s.clear()
  1311. # returns noValue
  1312. s.getComponentByPosition(0, instantiate=False)
  1313. """
  1314. try:
  1315. componentValue = self._componentValues[idx]
  1316. except IndexError:
  1317. if not instantiate:
  1318. return default
  1319. self.setComponentByPosition(idx)
  1320. componentValue = self._componentValues[idx]
  1321. if default is noValue or componentValue.isValue:
  1322. return componentValue
  1323. else:
  1324. return default
  1325. def setComponentByPosition(self, idx, value=noValue,
  1326. verifyConstraints=True,
  1327. matchTags=True,
  1328. matchConstraints=True):
  1329. """Assign |ASN.1| type component by position.
  1330. Equivalent to Python sequence item assignment operation (e.g. `[]`)
  1331. or list.append() (when idx == len(self)).
  1332. Parameters
  1333. ----------
  1334. idx: :class:`int`
  1335. Component index (zero-based). Must either refer to existing
  1336. component or to N+1 component. In the latter case a new component
  1337. type gets instantiated (if *componentType* is set, or given ASN.1
  1338. object is taken otherwise) and appended to the |ASN.1| sequence.
  1339. Keyword Args
  1340. ------------
  1341. value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative
  1342. A Python value to initialize |ASN.1| component with (if *componentType* is set)
  1343. or ASN.1 value object to assign to |ASN.1| component.
  1344. verifyConstraints: :class:`bool`
  1345. If `False`, skip constraints validation
  1346. matchTags: :class:`bool`
  1347. If `False`, skip component tags matching
  1348. matchConstraints: :class:`bool`
  1349. If `False`, skip component constraints matching
  1350. Returns
  1351. -------
  1352. self
  1353. Raises
  1354. ------
  1355. IndexError:
  1356. When idx > len(self)
  1357. """
  1358. componentType = self.componentType
  1359. try:
  1360. currentValue = self._componentValues[idx]
  1361. except IndexError:
  1362. currentValue = noValue
  1363. if len(self._componentValues) < idx:
  1364. raise error.PyAsn1Error('Component index out of range')
  1365. if value is noValue:
  1366. if componentType is not None:
  1367. value = componentType.clone()
  1368. elif currentValue is noValue:
  1369. raise error.PyAsn1Error('Component type not defined')
  1370. elif not isinstance(value, base.Asn1Item):
  1371. if componentType is not None and isinstance(componentType, base.AbstractSimpleAsn1Item):
  1372. value = componentType.clone(value=value)
  1373. elif currentValue is not noValue and isinstance(currentValue, base.AbstractSimpleAsn1Item):
  1374. value = currentValue.clone(value=value)
  1375. else:
  1376. raise error.PyAsn1Error('Non-ASN.1 value %r and undefined component type at %r' % (value, self))
  1377. elif componentType is not None:
  1378. if self.strictConstraints:
  1379. if not componentType.isSameTypeWith(value, matchTags, matchConstraints):
  1380. raise error.PyAsn1Error('Component value is tag-incompatible: %r vs %r' % (value, componentType))
  1381. else:
  1382. if not componentType.isSuperTypeOf(value, matchTags, matchConstraints):
  1383. raise error.PyAsn1Error('Component value is tag-incompatible: %r vs %r' % (value, componentType))
  1384. if verifyConstraints and value.isValue:
  1385. try:
  1386. self.subtypeSpec(value, idx)
  1387. except error.PyAsn1Error:
  1388. exType, exValue, exTb = sys.exc_info()
  1389. raise exType('%s at %s' % (exValue, self.__class__.__name__))
  1390. if currentValue is noValue:
  1391. self._componentValues.append(value)
  1392. else:
  1393. self._componentValues[idx] = value
  1394. return self
  1395. @property
  1396. def componentTagMap(self):
  1397. if self.componentType is not None:
  1398. return self.componentType.tagMap
  1399. def prettyPrint(self, scope=0):
  1400. scope += 1
  1401. representation = self.__class__.__name__ + ':\n'
  1402. for idx, componentValue in enumerate(self._componentValues):
  1403. representation += ' ' * scope
  1404. if (componentValue is noValue and
  1405. self.componentType is not None):
  1406. representation += '<empty>'
  1407. else:
  1408. representation += componentValue.prettyPrint(scope)
  1409. return representation
  1410. def prettyPrintType(self, scope=0):
  1411. scope += 1
  1412. representation = '%s -> %s {\n' % (self.tagSet, self.__class__.__name__)
  1413. if self.componentType is not None:
  1414. representation += ' ' * scope
  1415. representation += self.componentType.prettyPrintType(scope)
  1416. return representation + '\n' + ' ' * (scope - 1) + '}'
  1417. @property
  1418. def isValue(self):
  1419. """Indicate that |ASN.1| object represents ASN.1 value.
  1420. If *isValue* is `False` then this object represents just ASN.1 schema.
  1421. If *isValue* is `True` then, in addition to its ASN.1 schema features,
  1422. this object can also be used like a Python built-in object (e.g. `int`,
  1423. `str`, `dict` etc.).
  1424. Returns
  1425. -------
  1426. : :class:`bool`
  1427. :class:`False` if object represents just ASN.1 schema.
  1428. :class:`True` if object represents ASN.1 schema and can be used as a normal value.
  1429. Note
  1430. ----
  1431. There is an important distinction between PyASN1 schema and value objects.
  1432. The PyASN1 schema objects can only participate in ASN.1 schema-related
  1433. operations (e.g. defining or testing the structure of the data). Most
  1434. obvious uses of ASN.1 schema is to guide serialisation codecs whilst
  1435. encoding/decoding serialised ASN.1 contents.
  1436. The PyASN1 value objects can **additionally** participate in many operations
  1437. involving regular Python objects (e.g. arithmetic, comprehension etc).
  1438. """
  1439. for componentValue in self._componentValues:
  1440. if componentValue is noValue or not componentValue.isValue:
  1441. return False
  1442. return True
  1443. class SequenceOf(SequenceOfAndSetOfBase):
  1444. __doc__ = SequenceOfAndSetOfBase.__doc__
  1445. #: Set (on class, not on instance) or return a
  1446. #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s)
  1447. #: associated with |ASN.1| type.
  1448. tagSet = tag.initTagSet(
  1449. tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x10)
  1450. )
  1451. #: Default :py:class:`~pyasn1.type.base.PyAsn1Item` derivative
  1452. #: object representing ASN.1 type allowed within |ASN.1| type
  1453. componentType = None
  1454. #: Set (on class, not on instance) or return a
  1455. #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object
  1456. #: imposing constraints on |ASN.1| type initialization values.
  1457. subtypeSpec = constraint.ConstraintsIntersection()
  1458. #: Default :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
  1459. #: object imposing size constraint on |ASN.1| objects
  1460. sizeSpec = constraint.ConstraintsIntersection()
  1461. # Disambiguation ASN.1 types identification
  1462. typeId = SequenceOfAndSetOfBase.getTypeId()
  1463. class SetOf(SequenceOfAndSetOfBase):
  1464. __doc__ = SequenceOfAndSetOfBase.__doc__
  1465. #: Set (on class, not on instance) or return a
  1466. #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s)
  1467. #: associated with |ASN.1| type.
  1468. tagSet = tag.initTagSet(
  1469. tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x11)
  1470. )
  1471. #: Default :py:class:`~pyasn1.type.base.PyAsn1Item` derivative
  1472. #: object representing ASN.1 type allowed within |ASN.1| type
  1473. componentType = None
  1474. #: Set (on class, not on instance) or return a
  1475. #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object
  1476. #: imposing constraints on |ASN.1| type initialization values.
  1477. subtypeSpec = constraint.ConstraintsIntersection()
  1478. #: Default :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
  1479. #: object imposing size constraint on |ASN.1| objects
  1480. sizeSpec = constraint.ConstraintsIntersection()
  1481. # Disambiguation ASN.1 types identification
  1482. typeId = SequenceOfAndSetOfBase.getTypeId()
  1483. class SequenceAndSetBase(base.AbstractConstructedAsn1Item):
  1484. """Create |ASN.1| type.
  1485. |ASN.1| objects are mutable and duck-type Python :class:`dict` objects.
  1486. Keyword Args
  1487. ------------
  1488. componentType: :py:class:`~pyasn1.type.namedtype.NamedType`
  1489. Object holding named ASN.1 types allowed within this collection
  1490. tagSet: :py:class:`~pyasn1.type.tag.TagSet`
  1491. Object representing non-default ASN.1 tag(s)
  1492. subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
  1493. Object representing non-default ASN.1 subtype constraint(s)
  1494. sizeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
  1495. Object representing collection size constraint
  1496. Examples
  1497. --------
  1498. .. code-block:: python
  1499. class Description(Sequence): # Set is similar
  1500. '''
  1501. ASN.1 specification:
  1502. Description ::= SEQUENCE {
  1503. surname IA5String,
  1504. first-name IA5String OPTIONAL,
  1505. age INTEGER DEFAULT 40
  1506. }
  1507. '''
  1508. componentType = NamedTypes(
  1509. NamedType('surname', IA5String()),
  1510. OptionalNamedType('first-name', IA5String()),
  1511. DefaultedNamedType('age', Integer(40))
  1512. )
  1513. descr = Description()
  1514. descr['surname'] = 'Smith'
  1515. descr['first-name'] = 'John'
  1516. """
  1517. #: Default :py:class:`~pyasn1.type.namedtype.NamedTypes`
  1518. #: object representing named ASN.1 types allowed within |ASN.1| type
  1519. componentType = namedtype.NamedTypes()
  1520. class DynamicNames(object):
  1521. """Fields names/positions mapping for component-less objects"""
  1522. def __init__(self):
  1523. self._keyToIdxMap = {}
  1524. self._idxToKeyMap = {}
  1525. def __len__(self):
  1526. return len(self._keyToIdxMap)
  1527. def __contains__(self, item):
  1528. return item in self._keyToIdxMap or item in self._idxToKeyMap
  1529. def __iter__(self):
  1530. return (self._idxToKeyMap[idx] for idx in range(len(self._idxToKeyMap)))
  1531. def __getitem__(self, item):
  1532. try:
  1533. return self._keyToIdxMap[item]
  1534. except KeyError:
  1535. return self._idxToKeyMap[item]
  1536. def getNameByPosition(self, idx):
  1537. try:
  1538. return self._idxToKeyMap[idx]
  1539. except KeyError:
  1540. raise error.PyAsn1Error('Type position out of range')
  1541. def getPositionByName(self, name):
  1542. try:
  1543. return self._keyToIdxMap[name]
  1544. except KeyError:
  1545. raise error.PyAsn1Error('Name %s not found' % (name,))
  1546. def addField(self, idx):
  1547. self._keyToIdxMap['field-%d' % idx] = idx
  1548. self._idxToKeyMap[idx] = 'field-%d' % idx
  1549. def __init__(self, **kwargs):
  1550. base.AbstractConstructedAsn1Item.__init__(self, **kwargs)
  1551. self._componentTypeLen = len(self.componentType)
  1552. self._dynamicNames = self._componentTypeLen or self.DynamicNames()
  1553. def __getitem__(self, idx):
  1554. if octets.isStringType(idx):
  1555. try:
  1556. return self.getComponentByName(idx)
  1557. except error.PyAsn1Error:
  1558. # duck-typing dict
  1559. raise KeyError(sys.exc_info()[1])
  1560. else:
  1561. try:
  1562. return self.getComponentByPosition(idx)
  1563. except error.PyAsn1Error:
  1564. # duck-typing list
  1565. raise IndexError(sys.exc_info()[1])
  1566. def __setitem__(self, idx, value):
  1567. if octets.isStringType(idx):
  1568. try:
  1569. self.setComponentByName(idx, value)
  1570. except error.PyAsn1Error:
  1571. # duck-typing dict
  1572. raise KeyError(sys.exc_info()[1])
  1573. else:
  1574. try:
  1575. self.setComponentByPosition(idx, value)
  1576. except error.PyAsn1Error:
  1577. # duck-typing list
  1578. raise IndexError(sys.exc_info()[1])
  1579. def __contains__(self, key):
  1580. if self._componentTypeLen:
  1581. return key in self.componentType
  1582. else:
  1583. return key in self._dynamicNames
  1584. def __iter__(self):
  1585. return iter(self.componentType or self._dynamicNames)
  1586. # Python dict protocol
  1587. def values(self):
  1588. for idx in range(self._componentTypeLen or len(self._dynamicNames)):
  1589. yield self[idx]
  1590. def keys(self):
  1591. return iter(self)
  1592. def items(self):
  1593. for idx in range(self._componentTypeLen or len(self._dynamicNames)):
  1594. if self._componentTypeLen:
  1595. yield self.componentType[idx].name, self[idx]
  1596. else:
  1597. yield self._dynamicNames[idx], self[idx]
  1598. def update(self, *iterValue, **mappingValue):
  1599. for k, v in iterValue:
  1600. self[k] = v
  1601. for k in mappingValue:
  1602. self[k] = mappingValue[k]
  1603. def clear(self):
  1604. self._componentValues = []
  1605. self._dynamicNames = self.DynamicNames()
  1606. def _cloneComponentValues(self, myClone, cloneValueFlag):
  1607. for idx, componentValue in enumerate(self._componentValues):
  1608. if componentValue is not noValue:
  1609. if isinstance(componentValue, base.AbstractConstructedAsn1Item):
  1610. myClone.setComponentByPosition(
  1611. idx, componentValue.clone(cloneValueFlag=cloneValueFlag)
  1612. )
  1613. else:
  1614. myClone.setComponentByPosition(idx, componentValue.clone())
  1615. def getComponentByName(self, name, default=noValue, instantiate=True):
  1616. """Returns |ASN.1| type component by name.
  1617. Equivalent to Python :class:`dict` subscription operation (e.g. `[]`).
  1618. Parameters
  1619. ----------
  1620. name: :class:`str`
  1621. |ASN.1| type component name
  1622. Keyword Args
  1623. ------------
  1624. default: :class:`object`
  1625. If set and requested component is a schema object, return the `default`
  1626. object instead of the requested component.
  1627. instantiate: :class:`bool`
  1628. If `True` (default), inner component will be automatically instantiated.
  1629. If 'False' either existing component or the `noValue` object will be
  1630. returned.
  1631. Returns
  1632. -------
  1633. : :py:class:`~pyasn1.type.base.PyAsn1Item`
  1634. Instantiate |ASN.1| component type or return existing component value
  1635. """
  1636. if self._componentTypeLen:
  1637. idx = self.componentType.getPositionByName(name)
  1638. else:
  1639. try:
  1640. idx = self._dynamicNames.getPositionByName(name)
  1641. except KeyError:
  1642. raise error.PyAsn1Error('Name %s not found' % (name,))
  1643. return self.getComponentByPosition(idx, default=default, instantiate=instantiate)
  1644. def setComponentByName(self, name, value=noValue,
  1645. verifyConstraints=True,
  1646. matchTags=True,
  1647. matchConstraints=True):
  1648. """Assign |ASN.1| type component by name.
  1649. Equivalent to Python :class:`dict` item assignment operation (e.g. `[]`).
  1650. Parameters
  1651. ----------
  1652. name: :class:`str`
  1653. |ASN.1| type component name
  1654. Keyword Args
  1655. ------------
  1656. value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative
  1657. A Python value to initialize |ASN.1| component with (if *componentType* is set)
  1658. or ASN.1 value object to assign to |ASN.1| component.
  1659. verifyConstraints: :class:`bool`
  1660. If `False`, skip constraints validation
  1661. matchTags: :class:`bool`
  1662. If `False`, skip component tags matching
  1663. matchConstraints: :class:`bool`
  1664. If `False`, skip component constraints matching
  1665. Returns
  1666. -------
  1667. self
  1668. """
  1669. if self._componentTypeLen:
  1670. idx = self.componentType.getPositionByName(name)
  1671. else:
  1672. try:
  1673. idx = self._dynamicNames.getPositionByName(name)
  1674. except KeyError:
  1675. raise error.PyAsn1Error('Name %s not found' % (name,))
  1676. return self.setComponentByPosition(
  1677. idx, value, verifyConstraints, matchTags, matchConstraints
  1678. )
  1679. def getComponentByPosition(self, idx, default=noValue, instantiate=True):
  1680. """Returns |ASN.1| type component by index.
  1681. Equivalent to Python sequence subscription operation (e.g. `[]`).
  1682. Parameters
  1683. ----------
  1684. idx: :class:`int`
  1685. Component index (zero-based). Must either refer to an existing
  1686. component or (if *componentType* is set) new ASN.1 schema object gets
  1687. instantiated.
  1688. Keyword Args
  1689. ------------
  1690. default: :class:`object`
  1691. If set and requested component is a schema object, return the `default`
  1692. object instead of the requested component.
  1693. instantiate: :class:`bool`
  1694. If `True` (default), inner component will be automatically instantiated.
  1695. If 'False' either existing component or the `noValue` object will be
  1696. returned.
  1697. Returns
  1698. -------
  1699. : :py:class:`~pyasn1.type.base.PyAsn1Item`
  1700. a PyASN1 object
  1701. Examples
  1702. --------
  1703. .. code-block:: python
  1704. # can also be Set
  1705. class MySequence(Sequence):
  1706. componentType = NamedTypes(
  1707. NamedType('id', OctetString())
  1708. )
  1709. s = MySequence()
  1710. # returns component #0 with `.isValue` property False
  1711. s.getComponentByPosition(0)
  1712. # returns None
  1713. s.getComponentByPosition(0, default=None)
  1714. s.clear()
  1715. # returns noValue
  1716. s.getComponentByPosition(0, instantiate=False)
  1717. # sets component #0 to OctetString() ASN.1 schema
  1718. # object and returns it
  1719. s.getComponentByPosition(0, instantiate=True)
  1720. # sets component #0 to ASN.1 value object
  1721. s.setComponentByPosition(0, 'ABCD')
  1722. # returns OctetString('ABCD') value object
  1723. s.getComponentByPosition(0, instantiate=False)
  1724. s.clear()
  1725. # returns noValue
  1726. s.getComponentByPosition(0, instantiate=False)
  1727. """
  1728. try:
  1729. componentValue = self._componentValues[idx]
  1730. except IndexError:
  1731. componentValue = noValue
  1732. if not instantiate:
  1733. if componentValue is noValue or not componentValue.isValue:
  1734. return default
  1735. else:
  1736. return componentValue
  1737. if componentValue is noValue:
  1738. self.setComponentByPosition(idx)
  1739. componentValue = self._componentValues[idx]
  1740. if default is noValue or componentValue.isValue:
  1741. return componentValue
  1742. else:
  1743. return default
  1744. def setComponentByPosition(self, idx, value=noValue,
  1745. verifyConstraints=True,
  1746. matchTags=True,
  1747. matchConstraints=True):
  1748. """Assign |ASN.1| type component by position.
  1749. Equivalent to Python sequence item assignment operation (e.g. `[]`).
  1750. Parameters
  1751. ----------
  1752. idx : :class:`int`
  1753. Component index (zero-based). Must either refer to existing
  1754. component (if *componentType* is set) or to N+1 component
  1755. otherwise. In the latter case a new component of given ASN.1
  1756. type gets instantiated and appended to |ASN.1| sequence.
  1757. Keyword Args
  1758. ------------
  1759. value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative
  1760. A Python value to initialize |ASN.1| component with (if *componentType* is set)
  1761. or ASN.1 value object to assign to |ASN.1| component.
  1762. verifyConstraints : :class:`bool`
  1763. If `False`, skip constraints validation
  1764. matchTags: :class:`bool`
  1765. If `False`, skip component tags matching
  1766. matchConstraints: :class:`bool`
  1767. If `False`, skip component constraints matching
  1768. Returns
  1769. -------
  1770. self
  1771. """
  1772. componentType = self.componentType
  1773. componentTypeLen = self._componentTypeLen
  1774. try:
  1775. currentValue = self._componentValues[idx]
  1776. except IndexError:
  1777. currentValue = noValue
  1778. if componentTypeLen:
  1779. if componentTypeLen < idx:
  1780. raise error.PyAsn1Error('component index out of range')
  1781. self._componentValues = [noValue] * componentTypeLen
  1782. if value is noValue:
  1783. if componentTypeLen:
  1784. value = componentType.getTypeByPosition(idx).clone()
  1785. elif currentValue is noValue:
  1786. raise error.PyAsn1Error('Component type not defined')
  1787. elif not isinstance(value, base.Asn1Item):
  1788. if componentTypeLen:
  1789. subComponentType = componentType.getTypeByPosition(idx)
  1790. if isinstance(subComponentType, base.AbstractSimpleAsn1Item):
  1791. value = subComponentType.clone(value=value)
  1792. else:
  1793. raise error.PyAsn1Error('%s can cast only scalar values' % componentType.__class__.__name__)
  1794. elif currentValue is not noValue and isinstance(currentValue, base.AbstractSimpleAsn1Item):
  1795. value = currentValue.clone(value=value)
  1796. else:
  1797. raise error.PyAsn1Error('%s undefined component type' % componentType.__class__.__name__)
  1798. elif (matchTags or matchConstraints) and componentTypeLen:
  1799. subComponentType = componentType.getTypeByPosition(idx)
  1800. if subComponentType is not noValue:
  1801. subtypeChecker = (self.strictConstraints and
  1802. subComponentType.isSameTypeWith or
  1803. subComponentType.isSuperTypeOf)
  1804. if not subtypeChecker(value, matchTags, matchConstraints):
  1805. if not componentType[idx].openType:
  1806. raise error.PyAsn1Error('Component value is tag-incompatible: %r vs %r' % (value, componentType))
  1807. if verifyConstraints and value.isValue:
  1808. try:
  1809. self.subtypeSpec(value, idx)
  1810. except error.PyAsn1Error:
  1811. exType, exValue, exTb = sys.exc_info()
  1812. raise exType('%s at %s' % (exValue, self.__class__.__name__))
  1813. if componentTypeLen or idx in self._dynamicNames:
  1814. self._componentValues[idx] = value
  1815. elif len(self._componentValues) == idx:
  1816. self._componentValues.append(value)
  1817. self._dynamicNames.addField(idx)
  1818. else:
  1819. raise error.PyAsn1Error('Component index out of range')
  1820. return self
  1821. @property
  1822. def isValue(self):
  1823. """Indicate that |ASN.1| object represents ASN.1 value.
  1824. If *isValue* is `False` then this object represents just ASN.1 schema.
  1825. If *isValue* is `True` then, in addition to its ASN.1 schema features,
  1826. this object can also be used like a Python built-in object (e.g. `int`,
  1827. `str`, `dict` etc.).
  1828. Returns
  1829. -------
  1830. : :class:`bool`
  1831. :class:`False` if object represents just ASN.1 schema.
  1832. :class:`True` if object represents ASN.1 schema and can be used as a normal value.
  1833. Note
  1834. ----
  1835. There is an important distinction between PyASN1 schema and value objects.
  1836. The PyASN1 schema objects can only participate in ASN.1 schema-related
  1837. operations (e.g. defining or testing the structure of the data). Most
  1838. obvious uses of ASN.1 schema is to guide serialisation codecs whilst
  1839. encoding/decoding serialised ASN.1 contents.
  1840. The PyASN1 value objects can **additionally** participate in many operations
  1841. involving regular Python objects (e.g. arithmetic, comprehension etc).
  1842. """
  1843. componentType = self.componentType
  1844. if componentType:
  1845. for idx, subComponentType in enumerate(componentType.namedTypes):
  1846. if subComponentType.isDefaulted or subComponentType.isOptional:
  1847. continue
  1848. if not self._componentValues:
  1849. return False
  1850. componentValue = self._componentValues[idx]
  1851. if componentValue is noValue or not componentValue.isValue:
  1852. return False
  1853. else:
  1854. for componentValue in self._componentValues:
  1855. if componentValue is noValue or not componentValue.isValue:
  1856. return False
  1857. return True
  1858. def prettyPrint(self, scope=0):
  1859. """Return an object representation string.
  1860. Returns
  1861. -------
  1862. : :class:`str`
  1863. Human-friendly object representation.
  1864. """
  1865. scope += 1
  1866. representation = self.__class__.__name__ + ':\n'
  1867. for idx, componentValue in enumerate(self._componentValues):
  1868. if componentValue is not noValue:
  1869. representation += ' ' * scope
  1870. if self.componentType:
  1871. representation += self.componentType.getNameByPosition(idx)
  1872. else:
  1873. representation += self._dynamicNames.getNameByPosition(idx)
  1874. representation = '%s=%s\n' % (
  1875. representation, componentValue.prettyPrint(scope)
  1876. )
  1877. return representation
  1878. def prettyPrintType(self, scope=0):
  1879. scope += 1
  1880. representation = '%s -> %s {\n' % (self.tagSet, self.__class__.__name__)
  1881. for idx, componentType in enumerate(self.componentType.values() or self._componentValues):
  1882. representation += ' ' * scope
  1883. if self.componentType:
  1884. representation += '"%s"' % self.componentType.getNameByPosition(idx)
  1885. else:
  1886. representation += '"%s"' % self._dynamicNames.getNameByPosition(idx)
  1887. representation = '%s = %s\n' % (
  1888. representation, componentType.prettyPrintType(scope)
  1889. )
  1890. return representation + '\n' + ' ' * (scope - 1) + '}'
  1891. # backward compatibility
  1892. def setDefaultComponents(self):
  1893. return self
  1894. def getComponentType(self):
  1895. if self._componentTypeLen:
  1896. return self.componentType
  1897. def getNameByPosition(self, idx):
  1898. if self._componentTypeLen:
  1899. return self.componentType[idx].name
  1900. class Sequence(SequenceAndSetBase):
  1901. __doc__ = SequenceAndSetBase.__doc__
  1902. #: Set (on class, not on instance) or return a
  1903. #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s)
  1904. #: associated with |ASN.1| type.
  1905. tagSet = tag.initTagSet(
  1906. tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x10)
  1907. )
  1908. #: Set (on class, not on instance) or return a
  1909. #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object
  1910. #: imposing constraints on |ASN.1| type initialization values.
  1911. subtypeSpec = constraint.ConstraintsIntersection()
  1912. #: Default :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
  1913. #: object imposing constraints on |ASN.1| objects
  1914. sizeSpec = constraint.ConstraintsIntersection()
  1915. #: Default collection of ASN.1 types of component (e.g. :py:class:`~pyasn1.type.namedtype.NamedType`)
  1916. #: object imposing size constraint on |ASN.1| objects
  1917. componentType = namedtype.NamedTypes()
  1918. # Disambiguation ASN.1 types identification
  1919. typeId = SequenceAndSetBase.getTypeId()
  1920. # backward compatibility
  1921. def getComponentTagMapNearPosition(self, idx):
  1922. if self.componentType:
  1923. return self.componentType.getTagMapNearPosition(idx)
  1924. def getComponentPositionNearType(self, tagSet, idx):
  1925. if self.componentType:
  1926. return self.componentType.getPositionNearType(tagSet, idx)
  1927. else:
  1928. return idx
  1929. class Set(SequenceAndSetBase):
  1930. __doc__ = SequenceAndSetBase.__doc__
  1931. #: Set (on class, not on instance) or return a
  1932. #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s)
  1933. #: associated with |ASN.1| type.
  1934. tagSet = tag.initTagSet(
  1935. tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x11)
  1936. )
  1937. #: Default collection of ASN.1 types of component (e.g. :py:class:`~pyasn1.type.namedtype.NamedType`)
  1938. #: object representing ASN.1 type allowed within |ASN.1| type
  1939. componentType = namedtype.NamedTypes()
  1940. #: Set (on class, not on instance) or return a
  1941. #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object
  1942. #: imposing constraints on |ASN.1| type initialization values.
  1943. subtypeSpec = constraint.ConstraintsIntersection()
  1944. #: Default :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
  1945. #: object imposing constraints on |ASN.1| objects
  1946. sizeSpec = constraint.ConstraintsIntersection()
  1947. # Disambiguation ASN.1 types identification
  1948. typeId = SequenceAndSetBase.getTypeId()
  1949. def getComponent(self, innerFlag=False):
  1950. return self
  1951. def getComponentByType(self, tagSet, default=noValue,
  1952. instantiate=True, innerFlag=False):
  1953. """Returns |ASN.1| type component by ASN.1 tag.
  1954. Parameters
  1955. ----------
  1956. tagSet : :py:class:`~pyasn1.type.tag.TagSet`
  1957. Object representing ASN.1 tags to identify one of
  1958. |ASN.1| object component
  1959. Keyword Args
  1960. ------------
  1961. default: :class:`object`
  1962. If set and requested component is a schema object, return the `default`
  1963. object instead of the requested component.
  1964. instantiate: :class:`bool`
  1965. If `True` (default), inner component will be automatically instantiated.
  1966. If 'False' either existing component or the `noValue` object will be
  1967. returned.
  1968. Returns
  1969. -------
  1970. : :py:class:`~pyasn1.type.base.PyAsn1Item`
  1971. a pyasn1 object
  1972. """
  1973. componentValue = self.getComponentByPosition(
  1974. self.componentType.getPositionByType(tagSet),
  1975. default=default, instantiate=instantiate
  1976. )
  1977. if innerFlag and isinstance(componentValue, Set):
  1978. # get inner component by inner tagSet
  1979. return componentValue.getComponent(innerFlag=True)
  1980. else:
  1981. # get outer component by inner tagSet
  1982. return componentValue
  1983. def setComponentByType(self, tagSet, value=noValue,
  1984. verifyConstraints=True,
  1985. matchTags=True,
  1986. matchConstraints=True,
  1987. innerFlag=False):
  1988. """Assign |ASN.1| type component by ASN.1 tag.
  1989. Parameters
  1990. ----------
  1991. tagSet : :py:class:`~pyasn1.type.tag.TagSet`
  1992. Object representing ASN.1 tags to identify one of
  1993. |ASN.1| object component
  1994. Keyword Args
  1995. ------------
  1996. value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative
  1997. A Python value to initialize |ASN.1| component with (if *componentType* is set)
  1998. or ASN.1 value object to assign to |ASN.1| component.
  1999. verifyConstraints : :class:`bool`
  2000. If `False`, skip constraints validation
  2001. matchTags: :class:`bool`
  2002. If `False`, skip component tags matching
  2003. matchConstraints: :class:`bool`
  2004. If `False`, skip component constraints matching
  2005. innerFlag: :class:`bool`
  2006. If `True`, search for matching *tagSet* recursively.
  2007. Returns
  2008. -------
  2009. self
  2010. """
  2011. idx = self.componentType.getPositionByType(tagSet)
  2012. if innerFlag: # set inner component by inner tagSet
  2013. componentType = self.componentType.getTypeByPosition(idx)
  2014. if componentType.tagSet:
  2015. return self.setComponentByPosition(
  2016. idx, value, verifyConstraints, matchTags, matchConstraints
  2017. )
  2018. else:
  2019. componentType = self.getComponentByPosition(idx)
  2020. return componentType.setComponentByType(
  2021. tagSet, value, verifyConstraints, matchTags, matchConstraints, innerFlag=innerFlag
  2022. )
  2023. else: # set outer component by inner tagSet
  2024. return self.setComponentByPosition(
  2025. idx, value, verifyConstraints, matchTags, matchConstraints
  2026. )
  2027. @property
  2028. def componentTagMap(self):
  2029. if self.componentType:
  2030. return self.componentType.tagMapUnique
  2031. class Choice(Set):
  2032. """Create |ASN.1| type.
  2033. |ASN.1| objects are mutable and duck-type Python :class:`dict` objects.
  2034. Keyword Args
  2035. ------------
  2036. componentType: :py:class:`~pyasn1.type.namedtype.NamedType`
  2037. Object holding named ASN.1 types allowed within this collection
  2038. tagSet: :py:class:`~pyasn1.type.tag.TagSet`
  2039. Object representing non-default ASN.1 tag(s)
  2040. subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
  2041. Object representing non-default ASN.1 subtype constraint(s)
  2042. sizeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
  2043. Object representing collection size constraint
  2044. Examples
  2045. --------
  2046. .. code-block:: python
  2047. class Afters(Choice):
  2048. '''
  2049. ASN.1 specification:
  2050. Afters ::= CHOICE {
  2051. cheese [0] IA5String,
  2052. dessert [1] IA5String
  2053. }
  2054. '''
  2055. componentType = NamedTypes(
  2056. NamedType('cheese', IA5String().subtype(
  2057. implicitTag=Tag(tagClassContext, tagFormatSimple, 0)
  2058. ),
  2059. NamedType('dessert', IA5String().subtype(
  2060. implicitTag=Tag(tagClassContext, tagFormatSimple, 1)
  2061. )
  2062. )
  2063. afters = Afters()
  2064. afters['cheese'] = 'Mascarpone'
  2065. """
  2066. #: Set (on class, not on instance) or return a
  2067. #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s)
  2068. #: associated with |ASN.1| type.
  2069. tagSet = tag.TagSet() # untagged
  2070. #: Default collection of ASN.1 types of component (e.g. :py:class:`~pyasn1.type.namedtype.NamedType`)
  2071. #: object representing ASN.1 type allowed within |ASN.1| type
  2072. componentType = namedtype.NamedTypes()
  2073. #: Set (on class, not on instance) or return a
  2074. #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object
  2075. #: imposing constraints on |ASN.1| type initialization values.
  2076. subtypeSpec = constraint.ConstraintsIntersection()
  2077. #: Default :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
  2078. #: object imposing size constraint on |ASN.1| objects
  2079. sizeSpec = constraint.ConstraintsIntersection(
  2080. constraint.ValueSizeConstraint(1, 1)
  2081. )
  2082. # Disambiguation ASN.1 types identification
  2083. typeId = Set.getTypeId()
  2084. _currentIdx = None
  2085. def __eq__(self, other):
  2086. if self._componentValues:
  2087. return self._componentValues[self._currentIdx] == other
  2088. return NotImplemented
  2089. def __ne__(self, other):
  2090. if self._componentValues:
  2091. return self._componentValues[self._currentIdx] != other
  2092. return NotImplemented
  2093. def __lt__(self, other):
  2094. if self._componentValues:
  2095. return self._componentValues[self._currentIdx] < other
  2096. return NotImplemented
  2097. def __le__(self, other):
  2098. if self._componentValues:
  2099. return self._componentValues[self._currentIdx] <= other
  2100. return NotImplemented
  2101. def __gt__(self, other):
  2102. if self._componentValues:
  2103. return self._componentValues[self._currentIdx] > other
  2104. return NotImplemented
  2105. def __ge__(self, other):
  2106. if self._componentValues:
  2107. return self._componentValues[self._currentIdx] >= other
  2108. return NotImplemented
  2109. if sys.version_info[0] <= 2:
  2110. def __nonzero__(self):
  2111. return self._componentValues and True or False
  2112. else:
  2113. def __bool__(self):
  2114. return self._componentValues and True or False
  2115. def __len__(self):
  2116. return self._currentIdx is not None and 1 or 0
  2117. def __contains__(self, key):
  2118. if self._currentIdx is None:
  2119. return False
  2120. return key == self.componentType[self._currentIdx].getName()
  2121. def __iter__(self):
  2122. if self._currentIdx is None:
  2123. raise StopIteration
  2124. yield self.componentType[self._currentIdx].getName()
  2125. # Python dict protocol
  2126. def values(self):
  2127. if self._currentIdx is not None:
  2128. yield self._componentValues[self._currentIdx]
  2129. def keys(self):
  2130. if self._currentIdx is not None:
  2131. yield self.componentType[self._currentIdx].getName()
  2132. def items(self):
  2133. if self._currentIdx is not None:
  2134. yield self.componentType[self._currentIdx].getName(), self[self._currentIdx]
  2135. def verifySizeSpec(self):
  2136. if self._currentIdx is None:
  2137. raise error.PyAsn1Error('Component not chosen')
  2138. def _cloneComponentValues(self, myClone, cloneValueFlag):
  2139. try:
  2140. component = self.getComponent()
  2141. except error.PyAsn1Error:
  2142. pass
  2143. else:
  2144. if isinstance(component, Choice):
  2145. tagSet = component.effectiveTagSet
  2146. else:
  2147. tagSet = component.tagSet
  2148. if isinstance(component, base.AbstractConstructedAsn1Item):
  2149. myClone.setComponentByType(
  2150. tagSet, component.clone(cloneValueFlag=cloneValueFlag)
  2151. )
  2152. else:
  2153. myClone.setComponentByType(tagSet, component.clone())
  2154. def getComponentByPosition(self, idx, default=noValue, instantiate=True):
  2155. __doc__ = Set.__doc__
  2156. if self._currentIdx is None or self._currentIdx != idx:
  2157. return Set.getComponentByPosition(self, idx, default=default,
  2158. instantiate=instantiate)
  2159. return self._componentValues[idx]
  2160. def setComponentByPosition(self, idx, value=noValue,
  2161. verifyConstraints=True,
  2162. matchTags=True,
  2163. matchConstraints=True):
  2164. """Assign |ASN.1| type component by position.
  2165. Equivalent to Python sequence item assignment operation (e.g. `[]`).
  2166. Parameters
  2167. ----------
  2168. idx: :class:`int`
  2169. Component index (zero-based). Must either refer to existing
  2170. component or to N+1 component. In the latter case a new component
  2171. type gets instantiated (if *componentType* is set, or given ASN.1
  2172. object is taken otherwise) and appended to the |ASN.1| sequence.
  2173. Keyword Args
  2174. ------------
  2175. value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative
  2176. A Python value to initialize |ASN.1| component with (if *componentType* is set)
  2177. or ASN.1 value object to assign to |ASN.1| component. Once a new value is
  2178. set to *idx* component, previous value is dropped.
  2179. verifyConstraints : :class:`bool`
  2180. If `False`, skip constraints validation
  2181. matchTags: :class:`bool`
  2182. If `False`, skip component tags matching
  2183. matchConstraints: :class:`bool`
  2184. If `False`, skip component constraints matching
  2185. Returns
  2186. -------
  2187. self
  2188. """
  2189. oldIdx = self._currentIdx
  2190. Set.setComponentByPosition(self, idx, value, verifyConstraints, matchTags, matchConstraints)
  2191. self._currentIdx = idx
  2192. if oldIdx is not None and oldIdx != idx:
  2193. self._componentValues[oldIdx] = noValue
  2194. return self
  2195. @property
  2196. def effectiveTagSet(self):
  2197. """Return a :class:`~pyasn1.type.tag.TagSet` object of the currently initialized component or self (if |ASN.1| is tagged)."""
  2198. if self.tagSet:
  2199. return self.tagSet
  2200. else:
  2201. component = self.getComponent()
  2202. return component.effectiveTagSet
  2203. @property
  2204. def tagMap(self):
  2205. """"Return a :class:`~pyasn1.type.tagmap.TagMap` object mapping
  2206. ASN.1 tags to ASN.1 objects contained within callee.
  2207. """
  2208. if self.tagSet:
  2209. return Set.tagMap.fget(self)
  2210. else:
  2211. return self.componentType.tagMapUnique
  2212. def getComponent(self, innerFlag=False):
  2213. """Return currently assigned component of the |ASN.1| object.
  2214. Returns
  2215. -------
  2216. : :py:class:`~pyasn1.type.base.PyAsn1Item`
  2217. a PyASN1 object
  2218. """
  2219. if self._currentIdx is None:
  2220. raise error.PyAsn1Error('Component not chosen')
  2221. else:
  2222. c = self._componentValues[self._currentIdx]
  2223. if innerFlag and isinstance(c, Choice):
  2224. return c.getComponent(innerFlag)
  2225. else:
  2226. return c
  2227. def getName(self, innerFlag=False):
  2228. """Return the name of currently assigned component of the |ASN.1| object.
  2229. Returns
  2230. -------
  2231. : :py:class:`str`
  2232. |ASN.1| component name
  2233. """
  2234. if self._currentIdx is None:
  2235. raise error.PyAsn1Error('Component not chosen')
  2236. else:
  2237. if innerFlag:
  2238. c = self._componentValues[self._currentIdx]
  2239. if isinstance(c, Choice):
  2240. return c.getName(innerFlag)
  2241. return self.componentType.getNameByPosition(self._currentIdx)
  2242. @property
  2243. def isValue(self):
  2244. """Indicate that |ASN.1| object represents ASN.1 value.
  2245. If *isValue* is `False` then this object represents just ASN.1 schema.
  2246. If *isValue* is `True` then, in addition to its ASN.1 schema features,
  2247. this object can also be used like a Python built-in object (e.g. `int`,
  2248. `str`, `dict` etc.).
  2249. Returns
  2250. -------
  2251. : :class:`bool`
  2252. :class:`False` if object represents just ASN.1 schema.
  2253. :class:`True` if object represents ASN.1 schema and can be used as a normal value.
  2254. Note
  2255. ----
  2256. There is an important distinction between PyASN1 schema and value objects.
  2257. The PyASN1 schema objects can only participate in ASN.1 schema-related
  2258. operations (e.g. defining or testing the structure of the data). Most
  2259. obvious uses of ASN.1 schema is to guide serialisation codecs whilst
  2260. encoding/decoding serialised ASN.1 contents.
  2261. The PyASN1 value objects can **additionally** participate in many operations
  2262. involving regular Python objects (e.g. arithmetic, comprehension etc).
  2263. """
  2264. if self._currentIdx is None:
  2265. return False
  2266. componentValue = self._componentValues[self._currentIdx]
  2267. return componentValue is not noValue and componentValue.isValue
  2268. def clear(self):
  2269. self._currentIdx = None
  2270. Set.clear(self)
  2271. # compatibility stubs
  2272. def getMinTagSet(self):
  2273. return self.minTagSet
  2274. class Any(OctetString):
  2275. """Create |ASN.1| schema or value object.
  2276. |ASN.1| objects are immutable and duck-type Python 2 :class:`str` or Python 3
  2277. :class:`bytes`. When used in Unicode context, |ASN.1| type assumes "|encoding|"
  2278. serialisation.
  2279. Keyword Args
  2280. ------------
  2281. value: :class:`str`, :class:`bytes` or |ASN.1| object
  2282. string (Python 2) or bytes (Python 3), alternatively unicode object
  2283. (Python 2) or string (Python 3) representing character string to be
  2284. serialised into octets (note `encoding` parameter) or |ASN.1| object.
  2285. tagSet: :py:class:`~pyasn1.type.tag.TagSet`
  2286. Object representing non-default ASN.1 tag(s)
  2287. subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
  2288. Object representing non-default ASN.1 subtype constraint(s)
  2289. encoding: :py:class:`str`
  2290. Unicode codec ID to encode/decode :class:`unicode` (Python 2) or
  2291. :class:`str` (Python 3) the payload when |ASN.1| object is used
  2292. in text string context.
  2293. binValue: :py:class:`str`
  2294. Binary string initializer to use instead of the *value*.
  2295. Example: '10110011'.
  2296. hexValue: :py:class:`str`
  2297. Hexadecimal string initializer to use instead of the *value*.
  2298. Example: 'DEADBEEF'.
  2299. Raises
  2300. ------
  2301. :py:class:`~pyasn1.error.PyAsn1Error`
  2302. On constraint violation or bad initializer.
  2303. Examples
  2304. --------
  2305. .. code-block:: python
  2306. class Error(Sequence):
  2307. '''
  2308. ASN.1 specification:
  2309. Error ::= SEQUENCE {
  2310. code INTEGER,
  2311. parameter ANY DEFINED BY code -- Either INTEGER or REAL
  2312. }
  2313. '''
  2314. componentType=NamedTypes(
  2315. NamedType('code', Integer()),
  2316. NamedType('parameter', Any(),
  2317. openType=OpenType('code', {1: Integer(),
  2318. 2: Real()}))
  2319. )
  2320. error = Error()
  2321. error['code'] = 1
  2322. error['parameter'] = Integer(1234)
  2323. """
  2324. #: Set (on class, not on instance) or return a
  2325. #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s)
  2326. #: associated with |ASN.1| type.
  2327. tagSet = tag.TagSet() # untagged
  2328. #: Set (on class, not on instance) or return a
  2329. #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object
  2330. #: imposing constraints on |ASN.1| type initialization values.
  2331. subtypeSpec = constraint.ConstraintsIntersection()
  2332. # Disambiguation ASN.1 types identification
  2333. typeId = OctetString.getTypeId()
  2334. @property
  2335. def tagMap(self):
  2336. """"Return a :class:`~pyasn1.type.tagmap.TagMap` object mapping
  2337. ASN.1 tags to ASN.1 objects contained within callee.
  2338. """
  2339. try:
  2340. return self._tagMap
  2341. except AttributeError:
  2342. self._tagMap = tagmap.TagMap(
  2343. {self.tagSet: self},
  2344. {eoo.endOfOctets.tagSet: eoo.endOfOctets},
  2345. self
  2346. )
  2347. return self._tagMap
  2348. # XXX
  2349. # coercion rules?