Warning: file_get_contents(https://raw.githubusercontent.com/Den1xxx/Filemanager/master/languages/ru.json): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 88

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 215

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 216

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 217

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 218

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 219

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 220
PK!4񗪴6 phpunit.xmlnu刐迭 tests/unit src PK!h澭 README.mdnu刐迭# sebastian/type Collection of value objects that represent the types of the PHP type system. ## Installation You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/): ``` composer require sebastian/type ``` If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency: ``` composer require --dev sebastian/type ``` PK!蓾   phive.xmlnu刐迭 PK!$惢1LICENSEnu刐迭sebastian/type Copyright (c) 2019, Sebastian Bergmann . All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Sebastian Bergmann nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. PK!衟镻 tests/unit/IterableTypeTest.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type; use PHPUnit\Framework\TestCase; use SebastianBergmann\Type\TestFixture\Iterator; /** * @covers \SebastianBergmann\Type\IterableType * * @uses \SebastianBergmann\Type\Type * @uses \SebastianBergmann\Type\TypeName * @uses \SebastianBergmann\Type\ObjectType * @uses \SebastianBergmann\Type\SimpleType */ final class IterableTypeTest extends TestCase { /** * @var IterableType */ private $type; protected function setUp(): void { $this->type = new IterableType(false); } public function testMayDisallowNull(): void { $this->assertFalse($this->type->allowsNull()); } public function testCanGenerateReturnTypeDeclaration(): void { $this->assertEquals(': iterable', $this->type->getReturnTypeDeclaration()); } public function testMayAllowNull(): void { $type = new IterableType(true); $this->assertTrue($type->allowsNull()); } public function testCanGenerateNullableReturnTypeDeclaration(): void { $type = new IterableType(true); $this->assertEquals(': ?iterable', $type->getReturnTypeDeclaration()); } public function testNullCanBeAssignedToNullableIterable(): void { $type = new IterableType(true); $this->assertTrue($type->isAssignable(new NullType)); } public function testIterableCanBeAssignedToIterable(): void { $this->assertTrue($this->type->isAssignable(new IterableType(false))); } public function testArrayCanBeAssignedToIterable(): void { $this->assertTrue( $this->type->isAssignable( Type::fromValue([], false) ) ); } public function testIteratorCanBeAssignedToIterable(): void { $this->assertTrue( $this->type->isAssignable( Type::fromValue(new Iterator, false) ) ); } public function testSomethingThatIsNotIterableCannotBeAssignedToIterable(): void { $this->assertFalse( $this->type->isAssignable( Type::fromValue(null, false) ) ); } } PK!3etests/unit/SimpleTypeTest.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type; use PHPUnit\Framework\TestCase; /** * @covers \SebastianBergmann\Type\SimpleType * * @uses \SebastianBergmann\Type\Type */ final class SimpleTypeTest extends TestCase { public function testCanBeBool(): void { $type = new SimpleType('bool', false); $this->assertSame(': bool', $type->getReturnTypeDeclaration()); } public function testCanBeBoolean(): void { $type = new SimpleType('boolean', false); $this->assertSame(': bool', $type->getReturnTypeDeclaration()); } public function testCanBeDouble(): void { $type = new SimpleType('double', false); $this->assertSame(': float', $type->getReturnTypeDeclaration()); } public function testCanBeFloat(): void { $type = new SimpleType('float', false); $this->assertSame(': float', $type->getReturnTypeDeclaration()); } public function testCanBeReal(): void { $type = new SimpleType('real', false); $this->assertSame(': float', $type->getReturnTypeDeclaration()); } public function testCanBeInt(): void { $type = new SimpleType('int', false); $this->assertSame(': int', $type->getReturnTypeDeclaration()); } public function testCanBeInteger(): void { $type = new SimpleType('integer', false); $this->assertSame(': int', $type->getReturnTypeDeclaration()); } public function testCanBeArray(): void { $type = new SimpleType('array', false); $this->assertSame(': array', $type->getReturnTypeDeclaration()); } public function testCanBeArray2(): void { $type = new SimpleType('[]', false); $this->assertSame(': array', $type->getReturnTypeDeclaration()); } public function testMayAllowNull(): void { $type = new SimpleType('bool', true); $this->assertTrue($type->allowsNull()); $this->assertSame(': ?bool', $type->getReturnTypeDeclaration()); } public function testMayNotAllowNull(): void { $type = new SimpleType('bool', false); $this->assertFalse($type->allowsNull()); } /** * @dataProvider assignablePairs */ public function testIsAssignable(Type $assignTo, Type $assignedType): void { $this->assertTrue($assignTo->isAssignable($assignedType)); } public function assignablePairs(): array { return [ 'nullable to not nullable' => [new SimpleType('int', false), new SimpleType('int', true)], 'not nullable to nullable' => [new SimpleType('int', true), new SimpleType('int', false)], 'nullable to nullable' => [new SimpleType('int', true), new SimpleType('int', true)], 'not nullable to not nullable' => [new SimpleType('int', false), new SimpleType('int', false)], 'null to not nullable' => [new SimpleType('int', true), new NullType], ]; } /** * @dataProvider notAssignablePairs */ public function testIsNotAssignable(Type $assignTo, Type $assignedType): void { $this->assertFalse($assignTo->isAssignable($assignedType)); } public function notAssignablePairs(): array { return [ 'null to not nullable' => [new SimpleType('int', false), new NullType], 'int to boolean' => [new SimpleType('boolean', false), new SimpleType('int', false)], 'object' => [new SimpleType('boolean', false), new ObjectType(TypeName::fromQualifiedName(\stdClass::class), true)], 'unknown type' => [new SimpleType('boolean', false), new UnknownType], 'void' => [new SimpleType('boolean', false), new VoidType], ]; } /** * @dataProvider returnTypes */ public function testReturnTypeDeclaration(Type $type, string $returnType): void { $this->assertEquals($type->getReturnTypeDeclaration(), $returnType); } public function returnTypes(): array { return [ '[]' => [new SimpleType('[]', false), ': array'], 'array' => [new SimpleType('array', false), ': array'], '?array' => [new SimpleType('array', true), ': ?array'], 'boolean' => [new SimpleType('boolean', false), ': bool'], 'real' => [new SimpleType('real', false), ': float'], 'double' => [new SimpleType('double', false), ': float'], 'integer' => [new SimpleType('integer', false), ': int'], ]; } public function testCanHaveValue(): void { $this->assertSame('string', Type::fromValue('string', false)->value()); } } PK!Z[vAaa$tests/unit/GenericObjectTypeTest.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type; use PHPUnit\Framework\TestCase; /** * @covers \SebastianBergmann\Type\GenericObjectType * * @uses \SebastianBergmann\Type\Type * @uses \SebastianBergmann\Type\ObjectType * @uses \SebastianBergmann\Type\SimpleType * @uses \SebastianBergmann\Type\TypeName */ final class GenericObjectTypeTest extends TestCase { /** * @var GenericObjectType */ private $type; protected function setUp(): void { $this->type = new GenericObjectType(false); } public function testMayDisallowNull(): void { $this->assertFalse($this->type->allowsNull()); } public function testCanGenerateReturnTypeDeclaration(): void { $this->assertEquals(': object', $this->type->getReturnTypeDeclaration()); } public function testMayAllowNull(): void { $type = new GenericObjectType(true); $this->assertTrue($type->allowsNull()); } public function testCanGenerateNullableReturnTypeDeclaration(): void { $type = new GenericObjectType(true); $this->assertEquals(': ?object', $type->getReturnTypeDeclaration()); } public function testObjectCanBeAssignedToGenericObject(): void { $this->assertTrue( $this->type->isAssignable( new ObjectType(TypeName::fromQualifiedName(\stdClass::class), false) ) ); } public function testNullCanBeAssignedToNullableGenericObject(): void { $type = new GenericObjectType(true); $this->assertTrue( $type->isAssignable( new NullType ) ); } public function testNonObjectCannotBeAssignedToGenericObject(): void { $this->assertFalse( $this->type->isAssignable( new SimpleType('bool', false) ) ); } } PK!皴tests/unit/NullTypeTest.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type; use PHPUnit\Framework\TestCase; /** * @covers \SebastianBergmann\Type\NullType */ final class NullTypeTest extends TestCase { /** * @var NullType */ private $type; protected function setUp(): void { $this->type = new NullType; } /** * @dataProvider assignableTypes */ public function testIsAssignable(Type $assignableType): void { $this->assertTrue($this->type->isAssignable($assignableType)); } public function assignableTypes(): array { return [ [new SimpleType('int', false)], [new SimpleType('int', true)], [new ObjectType(TypeName::fromQualifiedName(self::class), false)], [new ObjectType(TypeName::fromQualifiedName(self::class), true)], [new UnknownType], ]; } /** * @dataProvider notAssignable */ public function testIsNotAssignable(Type $assignedType): void { $this->assertFalse($this->type->isAssignable($assignedType)); } public function notAssignable(): array { return [ 'void' => [new VoidType], ]; } public function testAllowsNull(): void { $this->assertTrue($this->type->allowsNull()); } public function testCanGenerateReturnTypeDeclaration(): void { $this->assertEquals('', $this->type->getReturnTypeDeclaration()); } } PK!'紳ddtests/unit/TypeNameTest.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type; use PHPUnit\Framework\TestCase; /** * @covers \SebastianBergmann\Type\TypeName */ final class TypeNameTest extends TestCase { public function testFromReflection(): void { $class = new \ReflectionClass(TypeName::class); $typeName = TypeName::fromReflection($class); $this->assertTrue($typeName->isNamespaced()); $this->assertEquals('SebastianBergmann\\Type', $typeName->getNamespaceName()); $this->assertEquals(TypeName::class, $typeName->getQualifiedName()); $this->assertEquals('TypeName', $typeName->getSimpleName()); } public function testFromQualifiedName(): void { $typeName = TypeName::fromQualifiedName('PHPUnit\\Framework\\MockObject\\TypeName'); $this->assertTrue($typeName->isNamespaced()); $this->assertEquals('PHPUnit\\Framework\\MockObject', $typeName->getNamespaceName()); $this->assertEquals('PHPUnit\\Framework\\MockObject\\TypeName', $typeName->getQualifiedName()); $this->assertEquals('TypeName', $typeName->getSimpleName()); } public function testFromQualifiedNameWithLeadingSeparator(): void { $typeName = TypeName::fromQualifiedName('\\Foo\\Bar'); $this->assertTrue($typeName->isNamespaced()); $this->assertEquals('Foo', $typeName->getNamespaceName()); $this->assertEquals('Foo\\Bar', $typeName->getQualifiedName()); $this->assertEquals('Bar', $typeName->getSimpleName()); } public function testFromQualifiedNameWithoutNamespace(): void { $typeName = TypeName::fromQualifiedName('Bar'); $this->assertFalse($typeName->isNamespaced()); $this->assertNull($typeName->getNamespaceName()); $this->assertEquals('Bar', $typeName->getQualifiedName()); $this->assertEquals('Bar', $typeName->getSimpleName()); } } PK! 籽tests/unit/TypeTest.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type; use PHPUnit\Framework\TestCase; /** * @covers \SebastianBergmann\Type\Type * * @uses \SebastianBergmann\Type\SimpleType * @uses \SebastianBergmann\Type\GenericObjectType * @uses \SebastianBergmann\Type\ObjectType * @uses \SebastianBergmann\Type\TypeName * @uses \SebastianBergmann\Type\CallableType * @uses \SebastianBergmann\Type\IterableType */ final class TypeTest extends TestCase { /** * @dataProvider valuesToNullableType */ public function testTypeMappingFromValue($value, bool $allowsNull, Type $expectedType): void { $this->assertEquals($expectedType, Type::fromValue($value, $allowsNull)); } public function valuesToNullableType(): array { return [ '?null' => [null, true, new NullType], 'null' => [null, false, new NullType], '?integer' => [1, true, new SimpleType('int', true, 1)], 'integer' => [1, false, new SimpleType('int', false, 1)], '?boolean' => [true, true, new SimpleType('bool', true, true)], 'boolean' => [true, false, new SimpleType('bool', false, true)], '?object' => [new \stdClass, true, new ObjectType(TypeName::fromQualifiedName(\stdClass::class), true)], 'object' => [new \stdClass, false, new ObjectType(TypeName::fromQualifiedName(\stdClass::class), false)], ]; } /** * @dataProvider namesToTypes */ public function testTypeMappingFromName(string $typeName, bool $allowsNull, $expectedType): void { $this->assertEquals($expectedType, Type::fromName($typeName, $allowsNull)); } public function namesToTypes(): array { return [ '?void' => ['void', true, new VoidType], 'void' => ['void', false, new VoidType], '?null' => ['null', true, new NullType], 'null' => ['null', true, new NullType], '?int' => ['int', true, new SimpleType('int', true)], '?integer' => ['integer', true, new SimpleType('int', true)], 'int' => ['int', false, new SimpleType('int', false)], 'bool' => ['bool', false, new SimpleType('bool', false)], 'boolean' => ['boolean', false, new SimpleType('bool', false)], 'object' => ['object', false, new GenericObjectType(false)], 'real' => ['real', false, new SimpleType('float', false)], 'double' => ['double', false, new SimpleType('float', false)], 'float' => ['float', false, new SimpleType('float', false)], 'string' => ['string', false, new SimpleType('string', false)], 'array' => ['array', false, new SimpleType('array', false)], 'resource' => ['resource', false, new SimpleType('resource', false)], 'resource (closed)' => ['resource (closed)', false, new SimpleType('resource (closed)', false)], 'unknown type' => ['unknown type', false, new UnknownType], '?classname' => [\stdClass::class, true, new ObjectType(TypeName::fromQualifiedName(\stdClass::class), true)], 'classname' => [\stdClass::class, false, new ObjectType(TypeName::fromQualifiedName(\stdClass::class), false)], 'callable' => ['callable', false, new CallableType(false)], '?callable' => ['callable', true, new CallableType(true)], 'iterable' => ['iterable', false, new IterableType(false)], '?iterable' => ['iterable', true, new IterableType(true)], ]; } } PK! )2''tests/unit/CallableTypeTest.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type; use PHPUnit\Framework\TestCase; use SebastianBergmann\Type\TestFixture\ClassWithCallbackMethods; use SebastianBergmann\Type\TestFixture\ClassWithInvokeMethod; /** * @covers \SebastianBergmann\Type\CallableType * * @uses \SebastianBergmann\Type\Type * @uses \SebastianBergmann\Type\ObjectType * @uses \SebastianBergmann\Type\SimpleType * @uses \SebastianBergmann\Type\TypeName */ final class CallableTypeTest extends TestCase { /** * @var CallableType */ private $type; protected function setUp(): void { $this->type = new CallableType(false); } public function testMayDisallowNull(): void { $this->assertFalse($this->type->allowsNull()); } public function testCanGenerateReturnTypeDeclaration(): void { $this->assertEquals(': callable', $this->type->getReturnTypeDeclaration()); } public function testMayAllowNull(): void { $type = new CallableType(true); $this->assertTrue($type->allowsNull()); } public function testCanGenerateNullableReturnTypeDeclaration(): void { $type = new CallableType(true); $this->assertEquals(': ?callable', $type->getReturnTypeDeclaration()); } public function testNullCanBeAssignedToNullableCallable(): void { $type = new CallableType(true); $this->assertTrue($type->isAssignable(new NullType)); } public function testCallableCanBeAssignedToCallable(): void { $this->assertTrue($this->type->isAssignable(new CallableType(false))); } public function testClosureCanBeAssignedToCallable(): void { $this->assertTrue( $this->type->isAssignable( new ObjectType( TypeName::fromQualifiedName(\Closure::class), false ) ) ); } public function testInvokableCanBeAssignedToCallable(): void { $this->assertTrue( $this->type->isAssignable( new ObjectType( TypeName::fromQualifiedName(ClassWithInvokeMethod::class), false ) ) ); } public function testStringWithFunctionNameCanBeAssignedToCallable(): void { $this->assertTrue( $this->type->isAssignable( Type::fromValue('SebastianBergmann\Type\TestFixture\callback_function', false) ) ); } public function testStringWithClassNameAndStaticMethodNameCanBeAssignedToCallable(): void { $this->assertTrue( $this->type->isAssignable( Type::fromValue(ClassWithCallbackMethods::class . '::staticCallback', false) ) ); } public function testArrayWithClassNameAndStaticMethodNameCanBeAssignedToCallable(): void { $this->assertTrue( $this->type->isAssignable( Type::fromValue([ClassWithCallbackMethods::class, 'staticCallback'], false) ) ); } public function testArrayWithClassNameAndInstanceMethodNameCanBeAssignedToCallable(): void { $this->assertTrue( $this->type->isAssignable( Type::fromValue([new ClassWithCallbackMethods, 'nonStaticCallback'], false) ) ); } public function testSomethingThatIsNotCallableCannotBeAssignedToCallable(): void { $this->assertFalse( $this->type->isAssignable( Type::fromValue(null, false) ) ); } public function testObjectWithoutInvokeMethodCannotBeAssignedToCallable(): void { $this->assertFalse( $this->type->isAssignable( Type::fromValue(new class { }, false) ) ); } } PK!浚,tests/unit/UnknownTypeTest.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type; use PHPUnit\Framework\TestCase; /** * @covers \SebastianBergmann\Type\UnknownType */ final class UnknownTypeTest extends TestCase { /** * @var UnknownType */ private $type; protected function setUp(): void { $this->type = new UnknownType; } /** * @dataProvider assignableTypes */ public function testIsAssignable(Type $assignableType): void { $this->assertTrue($this->type->isAssignable($assignableType)); } public function assignableTypes(): array { return [ [new SimpleType('int', false)], [new SimpleType('int', true)], [new VoidType], [new ObjectType(TypeName::fromQualifiedName(self::class), false)], [new ObjectType(TypeName::fromQualifiedName(self::class), true)], [new UnknownType], ]; } public function testAllowsNull(): void { $this->assertTrue($this->type->allowsNull()); } public function testReturnTypeDeclaration(): void { $this->assertEquals('', $this->type->getReturnTypeDeclaration()); } } PK!u挒綍tests/unit/VoidTypeTest.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type; use PHPUnit\Framework\TestCase; /** * @covers \SebastianBergmann\Type\VoidType */ final class VoidTypeTest extends TestCase { /** * @dataProvider assignableTypes */ public function testIsAssignable(Type $assignableType): void { $type = new VoidType; $this->assertTrue($type->isAssignable($assignableType)); } public function assignableTypes(): array { return [ [new VoidType], ]; } /** * @dataProvider notAssignableTypes */ public function testIsNotAssignable(Type $assignableType): void { $type = new VoidType; $this->assertFalse($type->isAssignable($assignableType)); } public function notAssignableTypes(): array { return [ [new SimpleType('int', false)], [new SimpleType('int', true)], [new ObjectType(TypeName::fromQualifiedName(self::class), false)], [new ObjectType(TypeName::fromQualifiedName(self::class), true)], [new UnknownType], ]; } public function testNotAllowNull(): void { $type = new VoidType; $this->assertFalse($type->allowsNull()); } public function testCanGenerateReturnTypeDeclaration(): void { $type = new VoidType; $this->assertEquals(': void', $type->getReturnTypeDeclaration()); } } PK!*琛摳tests/unit/ObjectTypeTest.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type; use PHPUnit\Framework\TestCase; use SebastianBergmann\Type\TestFixture\ChildClass; use SebastianBergmann\Type\TestFixture\ParentClass; /** * @covers \SebastianBergmann\Type\ObjectType * * @uses \SebastianBergmann\Type\TypeName * @uses \SebastianBergmann\Type\Type * @uses \SebastianBergmann\Type\SimpleType */ final class ObjectTypeTest extends TestCase { /** * @var ObjectType */ private $childClass; /** * @var ObjectType */ private $parentClass; protected function setUp(): void { $this->childClass = new ObjectType( TypeName::fromQualifiedName(ChildClass::class), false ); $this->parentClass = new ObjectType( TypeName::fromQualifiedName(ParentClass::class), false ); } public function testParentIsNotAssignableToChild(): void { $this->assertFalse($this->childClass->isAssignable($this->parentClass)); } public function testChildIsAssignableToParent(): void { $this->assertTrue($this->parentClass->isAssignable($this->childClass)); } public function testClassIsAssignableToSelf(): void { $this->assertTrue($this->parentClass->isAssignable($this->parentClass)); } public function testSimpleTypeIsNotAssignableToClass(): void { $this->assertFalse($this->parentClass->isAssignable(new SimpleType('int', false))); } public function testClassFromOneNamespaceIsNotAssignableToClassInOtherNamespace(): void { $classFromNamespaceA = new ObjectType( TypeName::fromQualifiedName(\someNamespaceA\NamespacedClass::class), false ); $classFromNamespaceB = new ObjectType( TypeName::fromQualifiedName(\someNamespaceB\NamespacedClass::class), false ); $this->assertFalse($classFromNamespaceA->isAssignable($classFromNamespaceB)); } public function testClassIsAssignableToSelfCaseInsensitively(): void { $classLowercased = new ObjectType( TypeName::fromQualifiedName(\strtolower(ParentClass::class)), false ); $this->assertTrue($this->parentClass->isAssignable($classLowercased)); } public function testNullIsAssignableToNullableType(): void { $someClass = new ObjectType( TypeName::fromQualifiedName(ParentClass::class), true ); $this->assertTrue($someClass->isAssignable(Type::fromValue(null, true))); } public function testNullIsNotAssignableToNotNullableType(): void { $someClass = new ObjectType( TypeName::fromQualifiedName(ParentClass::class), false ); $this->assertFalse($someClass->isAssignable(Type::fromValue(null, true))); } public function testPreservesNullNotAllowed(): void { $someClass = new ObjectType( TypeName::fromQualifiedName(ParentClass::class), false ); $this->assertFalse($someClass->allowsNull()); } public function testPreservesNullAllowed(): void { $someClass = new ObjectType( TypeName::fromQualifiedName(ParentClass::class), true ); $this->assertTrue($someClass->allowsNull()); } public function testCanGenerateReturnTypeDeclaration(): void { $this->assertEquals(': SebastianBergmann\Type\TestFixture\ParentClass', $this->parentClass->getReturnTypeDeclaration()); } public function testHasClassName(): void { $this->assertEquals('SebastianBergmann\Type\TestFixture\ParentClass', $this->parentClass->className()->getQualifiedName()); } } PK!瓌Luutests/_fixture/ParentClass.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type\TestFixture; class ParentClass { public function foo(): void { } } PK!櫬N藠(tests/_fixture/ClassWithInvokeMethod.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type\TestFixture; final class ClassWithInvokeMethod { public function __invoke(): void { } } PK! 8\\tests/_fixture/ChildClass.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type\TestFixture; class ChildClass extends ParentClass { } PK!誥!ZZ$tests/_fixture/callback_function.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type\TestFixture; function callback_function(): void { } PK!+tests/_fixture/ClassWithCallbackMethods.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type\TestFixture; final class ClassWithCallbackMethods { public static function staticCallback(): void { } public function nonStaticCallback(): void { } } PK!瓅饔KKtests/_fixture/Iterator.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type\TestFixture; final class Iterator implements \Iterator { public function current(): void { } public function next(): void { } public function key(): void { } public function valid(): void { } public function rewind(): void { } } PK!謣d .travis.ymlnu刐迭language: php php: - 7.2 - 7.3 - 7.4snapshot - nightly matrix: allow_failures: - php: master fast_finish: true env: matrix: - DEPENDENCIES="high" - DEPENDENCIES="low" global: - DEFAULT_COMPOSER_FLAGS="--no-interaction --no-ansi --no-progress --no-suggest" before_install: - ./tools/composer clear-cache install: - if [[ "$DEPENDENCIES" = 'high' ]]; then travis_retry ./tools/composer update $DEFAULT_COMPOSER_FLAGS; fi - if [[ "$DEPENDENCIES" = 'low' ]]; then travis_retry ./tools/composer update $DEFAULT_COMPOSER_FLAGS --prefer-lowest; fi script: - ./vendor/bin/phpunit --coverage-clover=coverage.xml after_success: - bash <(curl -s https://codecov.io/bash) notifications: email: false jobs: include: - stage: "Static Code Analysis" php: 7.3 env: php-cs-fixer install: - phpenv config-rm xdebug.ini script: - ./tools/php-cs-fixer fix --dry-run -v --show-progress=dots --diff-format=udiff - stage: "Static Code Analysis" php: 7.3 env: psalm install: - phpenv config-rm xdebug.ini script: - travis_retry ./tools/composer update $DEFAULT_COMPOSER_FLAGS - ./tools/psalm --shepherd --stats PK!o匵B .php_cs.distnu刐迭 For the full copyright and license information, please view the LICENSE file that was distributed with this source code. EOF; return PhpCsFixer\Config::create() ->setRiskyAllowed(true) ->setRules( [ 'align_multiline_comment' => true, 'array_indentation' => true, 'array_syntax' => ['syntax' => 'short'], 'binary_operator_spaces' => [ 'operators' => [ '=' => 'align', '=>' => 'align', ], ], 'blank_line_after_namespace' => true, 'blank_line_before_statement' => [ 'statements' => [ 'break', 'continue', 'declare', 'do', 'for', 'foreach', 'if', 'include', 'include_once', 'require', 'require_once', 'return', 'switch', 'throw', 'try', 'while', 'yield', ], ], 'braces' => true, 'cast_spaces' => true, 'class_attributes_separation' => ['elements' => ['const', 'method', 'property']], 'combine_consecutive_issets' => true, 'combine_consecutive_unsets' => true, 'compact_nullable_typehint' => true, 'concat_space' => ['spacing' => 'one'], 'declare_equal_normalize' => ['space' => 'none'], 'declare_strict_types' => true, 'dir_constant' => true, 'elseif' => true, 'encoding' => true, 'full_opening_tag' => true, 'function_declaration' => true, 'header_comment' => ['header' => $header, 'separate' => 'none'], 'indentation_type' => true, 'is_null' => true, 'line_ending' => true, 'list_syntax' => ['syntax' => 'short'], 'logical_operators' => true, 'lowercase_cast' => true, 'lowercase_constants' => true, 'lowercase_keywords' => true, 'lowercase_static_reference' => true, 'magic_constant_casing' => true, 'method_argument_space' => ['ensure_fully_multiline' => true], 'modernize_types_casting' => true, 'multiline_comment_opening_closing' => true, 'multiline_whitespace_before_semicolons' => true, 'native_constant_invocation' => true, 'native_function_casing' => true, 'native_function_invocation' => true, 'new_with_braces' => false, 'no_alias_functions' => true, 'no_alternative_syntax' => true, 'no_blank_lines_after_class_opening' => true, 'no_blank_lines_after_phpdoc' => true, 'no_blank_lines_before_namespace' => true, 'no_closing_tag' => true, 'no_empty_comment' => true, 'no_empty_phpdoc' => true, 'no_empty_statement' => true, 'no_extra_blank_lines' => true, 'no_homoglyph_names' => true, 'no_leading_import_slash' => true, 'no_leading_namespace_whitespace' => true, 'no_mixed_echo_print' => ['use' => 'print'], 'no_multiline_whitespace_around_double_arrow' => true, 'no_null_property_initialization' => true, 'no_php4_constructor' => true, 'no_short_bool_cast' => true, 'no_short_echo_tag' => true, 'no_singleline_whitespace_before_semicolons' => true, 'no_spaces_after_function_name' => true, 'no_spaces_inside_parenthesis' => true, 'no_superfluous_elseif' => true, 'no_superfluous_phpdoc_tags' => true, 'no_trailing_comma_in_list_call' => true, 'no_trailing_comma_in_singleline_array' => true, 'no_trailing_whitespace' => true, 'no_trailing_whitespace_in_comment' => true, 'no_unneeded_control_parentheses' => true, 'no_unneeded_curly_braces' => true, 'no_unneeded_final_method' => true, 'no_unreachable_default_argument_value' => true, 'no_unset_on_property' => true, 'no_unused_imports' => true, 'no_useless_else' => true, 'no_useless_return' => true, 'no_whitespace_before_comma_in_array' => true, 'no_whitespace_in_blank_line' => true, 'non_printable_character' => true, 'normalize_index_brace' => true, 'object_operator_without_whitespace' => true, 'ordered_class_elements' => [ 'order' => [ 'use_trait', 'constant_public', 'constant_protected', 'constant_private', 'property_public_static', 'property_protected_static', 'property_private_static', 'property_public', 'property_protected', 'property_private', 'method_public_static', 'construct', 'destruct', 'magic', 'phpunit', 'method_public', 'method_protected', 'method_private', 'method_protected_static', 'method_private_static', ], ], 'ordered_imports' => true, 'ordered_interfaces' => [ 'direction' => 'ascend', 'order' => 'alpha', ], 'phpdoc_add_missing_param_annotation' => true, 'phpdoc_align' => true, 'phpdoc_annotation_without_dot' => true, 'phpdoc_indent' => true, 'phpdoc_no_access' => true, 'phpdoc_no_empty_return' => true, 'phpdoc_no_package' => true, 'phpdoc_order' => true, 'phpdoc_return_self_reference' => true, 'phpdoc_scalar' => true, 'phpdoc_separation' => true, 'phpdoc_single_line_var_spacing' => true, 'phpdoc_to_comment' => true, 'phpdoc_trim' => true, 'phpdoc_trim_consecutive_blank_line_separation' => true, 'phpdoc_types' => ['groups' => ['simple', 'meta']], 'phpdoc_types_order' => true, 'phpdoc_var_without_name' => true, 'pow_to_exponentiation' => true, 'protected_to_private' => true, 'return_assignment' => true, 'return_type_declaration' => ['space_before' => 'none'], 'semicolon_after_instruction' => true, 'set_type_to_cast' => true, 'short_scalar_cast' => true, 'simplified_null_return' => true, 'single_blank_line_at_eof' => true, 'single_import_per_statement' => true, 'single_line_after_imports' => true, 'single_quote' => true, 'standardize_not_equals' => true, 'ternary_to_null_coalescing' => true, 'trailing_comma_in_multiline_array' => true, 'trim_array_spaces' => true, 'unary_operator_spaces' => true, 'visibility_required' => [ 'elements' => [ 'const', 'method', 'property', ], ], 'void_return' => true, 'whitespace_after_comma_in_array' => true, ] ) ->setFinder( PhpCsFixer\Finder::create() ->files() ->in(__DIR__ . '/src') ->in(__DIR__ . '/tests') ); PK!蝒伙cc composer.jsonnu刐迭{ "name": "sebastian/type", "description": "Collection of value objects that represent the types of the PHP type system", "type": "library", "homepage": "https://github.com/sebastianbergmann/type", "license": "BSD-3-Clause", "authors": [ { "name": "Sebastian Bergmann", "email": "sebastian@phpunit.de", "role": "lead" } ], "support": { "issues": "https://github.com/sebastianbergmann/type/issues" }, "prefer-stable": true, "require": { "php": "^7.2" }, "require-dev": { "phpunit/phpunit": "^8.2" }, "config": { "platform": { "php": "7.2.0" }, "optimize-autoloader": true, "sort-packages": true }, "autoload": { "classmap": [ "src/" ] }, "autoload-dev": { "classmap": [ "tests/_fixture" ], "files": [ "tests/_fixture/callback_function.php" ] }, "extra": { "branch-alias": { "dev-master": "1.1-dev" } } } PK!1酳).github/FUNDING.ymlnu刐迭patreon: s_bergmann PK!W/400 ChangeLog.mdnu刐迭# ChangeLog All notable changes are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles. ## [1.1.3] - 2019-07-02 ### Fixed * Fixed class name comparison in `ObjectType` to be case insensitive ## [1.1.2] - 2019-06-19 ### Fixed * Fixed handling of `object` type ## [1.1.1] - 2019-06-08 ### Fixed * Fixed autoloading of `callback_function.php` fixture file ## [1.1.0] - 2019-06-07 ### Added * Added support for `callable` type * Added support for `iterable` type ## [1.0.0] - 2019-06-06 * Initial release based on [code contributed by Michel Hartmann to PHPUnit](https://github.com/sebastianbergmann/phpunit/pull/3673) [1.1.3]: https://github.com/sebastianbergmann/type/compare/1.1.2...1.1.3 [1.1.2]: https://github.com/sebastianbergmann/type/compare/1.1.1...1.1.2 [1.1.1]: https://github.com/sebastianbergmann/type/compare/1.1.0...1.1.1 [1.1.0]: https://github.com/sebastianbergmann/type/compare/1.0.0...1.1.0 [1.0.0]: https://github.com/sebastianbergmann/type/compare/ff74aa41746bd8d10e931843ebf37d42da513ede...1.0.0 PK!蜰>src/TypeName.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type; final class TypeName { /** * @var ?string */ private $namespaceName; /** * @var string */ private $simpleName; public static function fromQualifiedName(string $fullClassName): self { if ($fullClassName[0] === '\\') { $fullClassName = \substr($fullClassName, 1); } $classNameParts = \explode('\\', $fullClassName); $simpleName = \array_pop($classNameParts); $namespaceName = \implode('\\', $classNameParts); return new self($namespaceName, $simpleName); } public static function fromReflection(\ReflectionClass $type): self { return new self( $type->getNamespaceName(), $type->getShortName() ); } public function __construct(?string $namespaceName, string $simpleName) { if ($namespaceName === '') { $namespaceName = null; } $this->namespaceName = $namespaceName; $this->simpleName = $simpleName; } public function getNamespaceName(): ?string { return $this->namespaceName; } public function getSimpleName(): string { return $this->simpleName; } public function getQualifiedName(): string { return $this->namespaceName === null ? $this->simpleName : $this->namespaceName . '\\' . $this->simpleName; } public function isNamespaced(): bool { return $this->namespaceName !== null; } } PK!)T[[src/VoidType.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type; final class VoidType extends Type { public function isAssignable(Type $other): bool { return $other instanceof self; } public function getReturnTypeDeclaration(): string { return ': void'; } public function allowsNull(): bool { return false; } } PK!彻璹QQsrc/IterableType.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type; final class IterableType extends Type { /** * @var bool */ private $allowsNull; public function __construct(bool $nullable) { $this->allowsNull = $nullable; } /** * @throws RuntimeException */ public function isAssignable(Type $other): bool { if ($this->allowsNull && $other instanceof NullType) { return true; } if ($other instanceof self) { return true; } if ($other instanceof SimpleType) { return \is_iterable($other->value()); } if ($other instanceof ObjectType) { try { return (new \ReflectionClass($other->className()->getQualifiedName()))->isIterable(); // @codeCoverageIgnoreStart } catch (\ReflectionException $e) { throw new RuntimeException( $e->getMessage(), (int) $e->getCode(), $e ); // @codeCoverageIgnoreEnd } } return false; } public function getReturnTypeDeclaration(): string { return ': ' . ($this->allowsNull ? '?' : '') . 'iterable'; } public function allowsNull(): bool { return $this->allowsNull; } } PK!9誳闧[src/NullType.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type; final class NullType extends Type { public function isAssignable(Type $other): bool { return !($other instanceof VoidType); } public function getReturnTypeDeclaration(): string { return ''; } public function allowsNull(): bool { return true; } } PK!艠1咤src/ObjectType.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type; final class ObjectType extends Type { /** * @var TypeName */ private $className; /** * @var bool */ private $allowsNull; public function __construct(TypeName $className, bool $allowsNull) { $this->className = $className; $this->allowsNull = $allowsNull; } public function isAssignable(Type $other): bool { if ($this->allowsNull && $other instanceof NullType) { return true; } if ($other instanceof self) { if (0 === \strcasecmp($this->className->getQualifiedName(), $other->className->getQualifiedName())) { return true; } if (\is_subclass_of($other->className->getQualifiedName(), $this->className->getQualifiedName(), true)) { return true; } } return false; } public function getReturnTypeDeclaration(): string { return ': ' . ($this->allowsNull ? '?' : '') . $this->className->getQualifiedName(); } public function allowsNull(): bool { return $this->allowsNull; } public function className(): TypeName { return $this->className; } } PK!螉]練src/CallableType.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type; final class CallableType extends Type { /** * @var bool */ private $allowsNull; public function __construct(bool $nullable) { $this->allowsNull = $nullable; } /** * @throws RuntimeException */ public function isAssignable(Type $other): bool { if ($this->allowsNull && $other instanceof NullType) { return true; } if ($other instanceof self) { return true; } if ($other instanceof ObjectType) { if ($this->isClosure($other)) { return true; } if ($this->hasInvokeMethod($other)) { return true; } } if ($other instanceof SimpleType) { if ($this->isFunction($other)) { return true; } if ($this->isClassCallback($other)) { return true; } if ($this->isObjectCallback($other)) { return true; } } return false; } public function getReturnTypeDeclaration(): string { return ': ' . ($this->allowsNull ? '?' : '') . 'callable'; } public function allowsNull(): bool { return $this->allowsNull; } private function isClosure(ObjectType $type): bool { return !$type->className()->isNamespaced() && $type->className()->getSimpleName() === \Closure::class; } /** * @throws RuntimeException */ private function hasInvokeMethod(ObjectType $type): bool { try { $class = new \ReflectionClass($type->className()->getQualifiedName()); // @codeCoverageIgnoreStart } catch (\ReflectionException $e) { throw new RuntimeException( $e->getMessage(), (int) $e->getCode(), $e ); // @codeCoverageIgnoreEnd } if ($class->hasMethod('__invoke')) { return true; } return false; } private function isFunction(SimpleType $type): bool { if (!\is_string($type->value())) { return false; } return \function_exists($type->value()); } private function isObjectCallback(SimpleType $type): bool { if (!\is_array($type->value())) { return false; } if (\count($type->value()) !== 2) { return false; } if (!\is_object($type->value()[0]) || !\is_string($type->value()[1])) { return false; } [$object, $methodName] = $type->value(); $reflector = new \ReflectionObject($object); return $reflector->hasMethod($methodName); } private function isClassCallback(SimpleType $type): bool { if (!\is_string($type->value()) && !\is_array($type->value())) { return false; } if (\is_string($type->value())) { if (\strpos($type->value(), '::') === false) { return false; } [$className, $methodName] = \explode('::', $type->value()); } if (\is_array($type->value())) { if (\count($type->value()) !== 2) { return false; } if (!\is_string($type->value()[0]) || !\is_string($type->value()[1])) { return false; } [$className, $methodName] = $type->value(); } \assert(isset($className) && \is_string($className)); \assert(isset($methodName) && \is_string($methodName)); try { $class = new \ReflectionClass($className); if ($class->hasMethod($methodName)) { $method = $class->getMethod($methodName); return $method->isPublic() && $method->isStatic(); } // @codeCoverageIgnoreStart } catch (\ReflectionException $e) { throw new RuntimeException( $e->getMessage(), (int) $e->getCode(), $e ); // @codeCoverageIgnoreEnd } return false; } } PK!k5 src/Type.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type; abstract class Type { public static function fromValue($value, bool $allowsNull): self { $typeName = \gettype($value); if ($typeName === 'object') { return new ObjectType(TypeName::fromQualifiedName(\get_class($value)), $allowsNull); } $type = self::fromName($typeName, $allowsNull); if ($type instanceof SimpleType) { $type = new SimpleType($typeName, $allowsNull, $value); } return $type; } public static function fromName(string $typeName, bool $allowsNull): self { switch (\strtolower($typeName)) { case 'callable': return new CallableType($allowsNull); case 'iterable': return new IterableType($allowsNull); case 'null': return new NullType; case 'object': return new GenericObjectType($allowsNull); case 'unknown type': return new UnknownType; case 'void': return new VoidType; case 'array': case 'bool': case 'boolean': case 'double': case 'float': case 'int': case 'integer': case 'real': case 'resource': case 'resource (closed)': case 'string': return new SimpleType($typeName, $allowsNull); default: return new ObjectType(TypeName::fromQualifiedName($typeName), $allowsNull); } } abstract public function isAssignable(Type $other): bool; abstract public function getReturnTypeDeclaration(): string; abstract public function allowsNull(): bool; } PK!56媴ww"src/exception/RuntimeException.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type; final class RuntimeException extends \RuntimeException implements Exception { } PK!Pm{??src/exception/Exception.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type; interface Exception { } PK!src/GenericObjectType.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type; final class GenericObjectType extends Type { /** * @var bool */ private $allowsNull; public function __construct(bool $nullable) { $this->allowsNull = $nullable; } public function isAssignable(Type $other): bool { if ($this->allowsNull && $other instanceof NullType) { return true; } if (!$other instanceof ObjectType) { return false; } return true; } public function getReturnTypeDeclaration(): string { return ': ' . ($this->allowsNull ? '?' : '') . 'object'; } public function allowsNull(): bool { return $this->allowsNull; } } PK! 猾EEsrc/UnknownType.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type; final class UnknownType extends Type { public function isAssignable(Type $other): bool { return true; } public function getReturnTypeDeclaration(): string { return ''; } public function allowsNull(): bool { return true; } } PK!g src/SimpleType.phpnu刐迭 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Type; final class SimpleType extends Type { /** * @var string */ private $name; /** * @var bool */ private $allowsNull; /** * @var mixed */ private $value; public function __construct(string $name, bool $nullable, $value = null) { $this->name = $this->normalize($name); $this->allowsNull = $nullable; $this->value = $value; } public function isAssignable(Type $other): bool { if ($this->allowsNull && $other instanceof NullType) { return true; } if ($other instanceof self) { return $this->name === $other->name; } return false; } public function getReturnTypeDeclaration(): string { return ': ' . ($this->allowsNull ? '?' : '') . $this->name; } public function allowsNull(): bool { return $this->allowsNull; } public function value() { return $this->value; } private function normalize(string $name): string { $name = \strtolower($name); switch ($name) { case 'boolean': return 'bool'; case 'real': case 'double': return 'float'; case 'integer': return 'int'; case '[]': return 'array'; default: return $name; } } } PK!罨 psalm.xmlnu刐迭 PK!鳘霉 build.xmlnu刐迭 PK!拿e9.gitattributesnu刐迭/tools export-ignore PK!婰馅 .gitignorenu刐迭/.php_cs /.php_cs.cache /.phpunit.result.cache /composer.lock /vendor # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 # User-specific stuff .idea/**/workspace.xml .idea/**/tasks.xml .idea/**/usage.statistics.xml .idea/**/dictionaries .idea/**/shelf # Generated files .idea/**/contentModel.xml # Sensitive or high-churn files .idea/**/dataSources/ .idea/**/dataSources.ids .idea/**/dataSources.local.xml .idea/**/sqlDataSources.xml .idea/**/dynamic.xml .idea/**/uiDesigner.xml .idea/**/dbnavigator.xml # Gradle .idea/**/gradle.xml .idea/**/libraries # Gradle and Maven with auto-import # When using Gradle or Maven with auto-import, you should exclude module files, # since they will be recreated, and may cause churn. Uncomment if using # auto-import. # .idea/modules.xml # .idea/*.iml # .idea/modules # CMake cmake-build-*/ # Mongo Explorer plugin .idea/**/mongoSettings.xml # File-based project format *.iws # IntelliJ out/ # mpeltonen/sbt-idea plugin .idea_modules/ # JIRA plugin atlassian-ide-plugin.xml # Cursive Clojure plugin .idea/replstate.xml # Crashlytics plugin (for Android Studio and IntelliJ) com_crashlytics_export_strings.xml crashlytics.properties crashlytics-build.properties fabric.properties # Editor-based Rest Client .idea/httpRequests # Android studio 3.1+ serialized cache file .idea/caches/build_file_checksums.ser PK!惀|xerror.pynu刐迭# # This file is part of pyasn1 software. # # Copyright (c) 2005-2020, Ilya Etingof # License: https://pyasn1.readthedocs.io/en/latest/license.html # from pyasn1.error import PyAsn1Error class ValueConstraintError(PyAsn1Error): pass PK!縚錄U沀 constraint.pynu刐迭# # This file is part of pyasn1 software. # # Copyright (c) 2005-2020, Ilya Etingof # License: https://pyasn1.readthedocs.io/en/latest/license.html # # Original concept and code by Mike C. Fletcher. # import sys from pyasn1.type import error __all__ = ['SingleValueConstraint', 'ContainedSubtypeConstraint', 'ValueRangeConstraint', 'ValueSizeConstraint', 'PermittedAlphabetConstraint', 'InnerTypeConstraint', 'ConstraintsExclusion', 'ConstraintsIntersection', 'ConstraintsUnion'] class AbstractConstraint(object): def __init__(self, *values): self._valueMap = set() self._setValues(values) self.__hash = hash((self.__class__.__name__, self._values)) def __call__(self, value, idx=None): if not self._values: return try: self._testValue(value, idx) except error.ValueConstraintError as exc: raise error.ValueConstraintError( '%s failed at: %r' % (self, exc) ) def __repr__(self): representation = '%s object' % (self.__class__.__name__) if self._values: representation += ', consts %s' % ', '.join( [repr(x) for x in self._values]) return '<%s>' % representation def __eq__(self, other): if self is other: return True return self._values == other def __ne__(self, other): return self._values != other def __lt__(self, other): return self._values < other def __le__(self, other): return self._values <= other def __gt__(self, other): return self._values > other def __ge__(self, other): return self._values >= other def __bool__(self): return bool(self._values) def __hash__(self): return self.__hash def _setValues(self, values): self._values = values def _testValue(self, value, idx): raise error.ValueConstraintError(value) # Constraints derivation logic def getValueMap(self): return self._valueMap def isSuperTypeOf(self, otherConstraint): # TODO: fix possible comparison of set vs scalars here return (otherConstraint is self or not self._values or otherConstraint == self or self in otherConstraint.getValueMap()) def isSubTypeOf(self, otherConstraint): return (otherConstraint is self or not self or otherConstraint == self or otherConstraint in self._valueMap) class SingleValueConstraint(AbstractConstraint): """Create a SingleValueConstraint object. The SingleValueConstraint satisfies any value that is present in the set of permitted values. Objects of this type are iterable (emitting constraint values) and can act as operands for some arithmetic operations e.g. addition and subtraction. The latter can be used for combining multiple SingleValueConstraint objects into one. The SingleValueConstraint object can be applied to any ASN.1 type. Parameters ---------- *values: :class:`int` Full set of values permitted by this constraint object. Examples -------- .. code-block:: python class DivisorOfSix(Integer): ''' ASN.1 specification: Divisor-Of-6 ::= INTEGER (1 | 2 | 3 | 6) ''' subtypeSpec = SingleValueConstraint(1, 2, 3, 6) # this will succeed divisor_of_six = DivisorOfSix(1) # this will raise ValueConstraintError divisor_of_six = DivisorOfSix(7) """ def _setValues(self, values): self._values = values self._set = set(values) def _testValue(self, value, idx): if value not in self._set: raise error.ValueConstraintError(value) # Constrains can be merged or reduced def __contains__(self, item): return item in self._set def __iter__(self): return iter(self._set) def __add__(self, constraint): return self.__class__(*(self._set.union(constraint))) def __sub__(self, constraint): return self.__class__(*(self._set.difference(constraint))) class ContainedSubtypeConstraint(AbstractConstraint): """Create a ContainedSubtypeConstraint object. The ContainedSubtypeConstraint satisfies any value that is present in the set of permitted values and also satisfies included constraints. The ContainedSubtypeConstraint object can be applied to any ASN.1 type. Parameters ---------- *values: Full set of values and constraint objects permitted by this constraint object. Examples -------- .. code-block:: python class DivisorOfEighteen(Integer): ''' ASN.1 specification: Divisors-of-18 ::= INTEGER (INCLUDES Divisors-of-6 | 9 | 18) ''' subtypeSpec = ContainedSubtypeConstraint( SingleValueConstraint(1, 2, 3, 6), 9, 18 ) # this will succeed divisor_of_eighteen = DivisorOfEighteen(9) # this will raise ValueConstraintError divisor_of_eighteen = DivisorOfEighteen(10) """ def _testValue(self, value, idx): for constraint in self._values: if isinstance(constraint, AbstractConstraint): constraint(value, idx) elif value not in self._set: raise error.ValueConstraintError(value) class ValueRangeConstraint(AbstractConstraint): """Create a ValueRangeConstraint object. The ValueRangeConstraint satisfies any value that falls in the range of permitted values. The ValueRangeConstraint object can only be applied to :class:`~pyasn1.type.univ.Integer` and :class:`~pyasn1.type.univ.Real` types. Parameters ---------- start: :class:`int` Minimum permitted value in the range (inclusive) end: :class:`int` Maximum permitted value in the range (inclusive) Examples -------- .. code-block:: python class TeenAgeYears(Integer): ''' ASN.1 specification: TeenAgeYears ::= INTEGER (13 .. 19) ''' subtypeSpec = ValueRangeConstraint(13, 19) # this will succeed teen_year = TeenAgeYears(18) # this will raise ValueConstraintError teen_year = TeenAgeYears(20) """ def _testValue(self, value, idx): if value < self.start or value > self.stop: raise error.ValueConstraintError(value) def _setValues(self, values): if len(values) != 2: raise error.PyAsn1Error( '%s: bad constraint values' % (self.__class__.__name__,) ) self.start, self.stop = values if self.start > self.stop: raise error.PyAsn1Error( '%s: screwed constraint values (start > stop): %s > %s' % ( self.__class__.__name__, self.start, self.stop ) ) AbstractConstraint._setValues(self, values) class ValueSizeConstraint(ValueRangeConstraint): """Create a ValueSizeConstraint object. The ValueSizeConstraint satisfies any value for as long as its size falls within the range of permitted sizes. The ValueSizeConstraint object can be applied to :class:`~pyasn1.type.univ.BitString`, :class:`~pyasn1.type.univ.OctetString` (including all :ref:`character ASN.1 types `), :class:`~pyasn1.type.univ.SequenceOf` and :class:`~pyasn1.type.univ.SetOf` types. Parameters ---------- minimum: :class:`int` Minimum permitted size of the value (inclusive) maximum: :class:`int` Maximum permitted size of the value (inclusive) Examples -------- .. code-block:: python class BaseballTeamRoster(SetOf): ''' ASN.1 specification: BaseballTeamRoster ::= SET SIZE (1..25) OF PlayerNames ''' componentType = PlayerNames() subtypeSpec = ValueSizeConstraint(1, 25) # this will succeed team = BaseballTeamRoster() team.extend(['Jan', 'Matej']) encode(team) # this will raise ValueConstraintError team = BaseballTeamRoster() team.extend(['Jan'] * 26) encode(team) Note ---- Whenever ValueSizeConstraint is applied to mutable types (e.g. :class:`~pyasn1.type.univ.SequenceOf`, :class:`~pyasn1.type.univ.SetOf`), constraint validation only happens at the serialisation phase rather than schema instantiation phase (as it is with immutable types). """ def _testValue(self, value, idx): valueSize = len(value) if valueSize < self.start or valueSize > self.stop: raise error.ValueConstraintError(value) class PermittedAlphabetConstraint(SingleValueConstraint): """Create a PermittedAlphabetConstraint object. The PermittedAlphabetConstraint satisfies any character string for as long as all its characters are present in the set of permitted characters. Objects of this type are iterable (emitting constraint values) and can act as operands for some arithmetic operations e.g. addition and subtraction. The PermittedAlphabetConstraint object can only be applied to the :ref:`character ASN.1 types ` such as :class:`~pyasn1.type.char.IA5String`. Parameters ---------- *alphabet: :class:`str` Full set of characters permitted by this constraint object. Example ------- .. code-block:: python class BooleanValue(IA5String): ''' ASN.1 specification: BooleanValue ::= IA5String (FROM ('T' | 'F')) ''' subtypeSpec = PermittedAlphabetConstraint('T', 'F') # this will succeed truth = BooleanValue('T') truth = BooleanValue('TF') # this will raise ValueConstraintError garbage = BooleanValue('TAF') ASN.1 `FROM ... EXCEPT ...` clause can be modelled by combining multiple PermittedAlphabetConstraint objects into one: Example ------- .. code-block:: python class Lipogramme(IA5String): ''' ASN.1 specification: Lipogramme ::= IA5String (FROM (ALL EXCEPT ("e"|"E"))) ''' subtypeSpec = ( PermittedAlphabetConstraint(*string.printable) - PermittedAlphabetConstraint('e', 'E') ) # this will succeed lipogramme = Lipogramme('A work of fiction?') # this will raise ValueConstraintError lipogramme = Lipogramme('Eel') Note ---- Although `ConstraintsExclusion` object could seemingly be used for this purpose, practically, for it to work, it needs to represent its operand constraints as sets and intersect one with the other. That would require the insight into the constraint values (and their types) that are otherwise hidden inside the constraint object. Therefore it's more practical to model `EXCEPT` clause at `PermittedAlphabetConstraint` level instead. """ def _setValues(self, values): self._values = values self._set = set(values) def _testValue(self, value, idx): if not self._set.issuperset(value): raise error.ValueConstraintError(value) class ComponentPresentConstraint(AbstractConstraint): """Create a ComponentPresentConstraint object. The ComponentPresentConstraint is only satisfied when the value is not `None`. The ComponentPresentConstraint object is typically used with `WithComponentsConstraint`. Examples -------- .. code-block:: python present = ComponentPresentConstraint() # this will succeed present('whatever') # this will raise ValueConstraintError present(None) """ def _setValues(self, values): self._values = ('',) if values: raise error.PyAsn1Error('No arguments expected') def _testValue(self, value, idx): if value is None: raise error.ValueConstraintError( 'Component is not present:') class ComponentAbsentConstraint(AbstractConstraint): """Create a ComponentAbsentConstraint object. The ComponentAbsentConstraint is only satisfied when the value is `None`. The ComponentAbsentConstraint object is typically used with `WithComponentsConstraint`. Examples -------- .. code-block:: python absent = ComponentAbsentConstraint() # this will succeed absent(None) # this will raise ValueConstraintError absent('whatever') """ def _setValues(self, values): self._values = ('',) if values: raise error.PyAsn1Error('No arguments expected') def _testValue(self, value, idx): if value is not None: raise error.ValueConstraintError( 'Component is not absent: %r' % value) class WithComponentsConstraint(AbstractConstraint): """Create a WithComponentsConstraint object. The `WithComponentsConstraint` satisfies any mapping object that has constrained fields present or absent, what is indicated by `ComponentPresentConstraint` and `ComponentAbsentConstraint` objects respectively. The `WithComponentsConstraint` object is typically applied to :class:`~pyasn1.type.univ.Set` or :class:`~pyasn1.type.univ.Sequence` types. Parameters ---------- *fields: :class:`tuple` Zero or more tuples of (`field`, `constraint`) indicating constrained fields. Notes ----- On top of the primary use of `WithComponentsConstraint` (ensuring presence or absence of particular components of a :class:`~pyasn1.type.univ.Set` or :class:`~pyasn1.type.univ.Sequence`), it is also possible to pass any other constraint objects or their combinations. In case of scalar fields, these constraints will be verified in addition to the constraints belonging to scalar components themselves. However, formally, these additional constraints do not change the type of these ASN.1 objects. Examples -------- .. code-block:: python class Item(Sequence): # Set is similar ''' ASN.1 specification: Item ::= SEQUENCE { id INTEGER OPTIONAL, name OCTET STRING OPTIONAL } WITH COMPONENTS id PRESENT, name ABSENT | id ABSENT, name PRESENT ''' componentType = NamedTypes( OptionalNamedType('id', Integer()), OptionalNamedType('name', OctetString()) ) withComponents = ConstraintsUnion( WithComponentsConstraint( ('id', ComponentPresentConstraint()), ('name', ComponentAbsentConstraint()) ), WithComponentsConstraint( ('id', ComponentAbsentConstraint()), ('name', ComponentPresentConstraint()) ) ) item = Item() # This will succeed item['id'] = 1 # This will succeed item.reset() item['name'] = 'John' # This will fail (on encoding) item.reset() descr['id'] = 1 descr['name'] = 'John' """ def _testValue(self, value, idx): for field, constraint in self._values: constraint(value.get(field)) def _setValues(self, values): AbstractConstraint._setValues(self, values) # This is a bit kludgy, meaning two op modes within a single constraint class InnerTypeConstraint(AbstractConstraint): """Value must satisfy the type and presence constraints""" def _testValue(self, value, idx): if self.__singleTypeConstraint: self.__singleTypeConstraint(value) elif self.__multipleTypeConstraint: if idx not in self.__multipleTypeConstraint: raise error.ValueConstraintError(value) constraint, status = self.__multipleTypeConstraint[idx] if status == 'ABSENT': # XXX presence is not checked! raise error.ValueConstraintError(value) constraint(value) def _setValues(self, values): self.__multipleTypeConstraint = {} self.__singleTypeConstraint = None for v in values: if isinstance(v, tuple): self.__multipleTypeConstraint[v[0]] = v[1], v[2] else: self.__singleTypeConstraint = v AbstractConstraint._setValues(self, values) # Logic operations on constraints class ConstraintsExclusion(AbstractConstraint): """Create a ConstraintsExclusion logic operator object. The ConstraintsExclusion logic operator succeeds when the value does *not* satisfy the operand constraint. The ConstraintsExclusion object can be applied to any constraint and logic operator object. Parameters ---------- *constraints: Constraint or logic operator objects. Examples -------- .. code-block:: python class LuckyNumber(Integer): subtypeSpec = ConstraintsExclusion( SingleValueConstraint(13) ) # this will succeed luckyNumber = LuckyNumber(12) # this will raise ValueConstraintError luckyNumber = LuckyNumber(13) Note ---- The `FROM ... EXCEPT ...` ASN.1 clause should be modeled by combining constraint objects into one. See `PermittedAlphabetConstraint` for more information. """ def _testValue(self, value, idx): for constraint in self._values: try: constraint(value, idx) except error.ValueConstraintError: continue raise error.ValueConstraintError(value) def _setValues(self, values): AbstractConstraint._setValues(self, values) class AbstractConstraintSet(AbstractConstraint): def __getitem__(self, idx): return self._values[idx] def __iter__(self): return iter(self._values) def __add__(self, value): return self.__class__(*(self._values + (value,))) def __radd__(self, value): return self.__class__(*((value,) + self._values)) def __len__(self): return len(self._values) # Constraints inclusion in sets def _setValues(self, values): self._values = values for constraint in values: if constraint: self._valueMap.add(constraint) self._valueMap.update(constraint.getValueMap()) class ConstraintsIntersection(AbstractConstraintSet): """Create a ConstraintsIntersection logic operator object. The ConstraintsIntersection logic operator only succeeds if *all* its operands succeed. The ConstraintsIntersection object can be applied to any constraint and logic operator objects. The ConstraintsIntersection object duck-types the immutable container object like Python :py:class:`tuple`. Parameters ---------- *constraints: Constraint or logic operator objects. Examples -------- .. code-block:: python class CapitalAndSmall(IA5String): ''' ASN.1 specification: CapitalAndSmall ::= IA5String (FROM ("A".."Z"|"a".."z")) ''' subtypeSpec = ConstraintsIntersection( PermittedAlphabetConstraint('A', 'Z'), PermittedAlphabetConstraint('a', 'z') ) # this will succeed capital_and_small = CapitalAndSmall('Hello') # this will raise ValueConstraintError capital_and_small = CapitalAndSmall('hello') """ def _testValue(self, value, idx): for constraint in self._values: constraint(value, idx) class ConstraintsUnion(AbstractConstraintSet): """Create a ConstraintsUnion logic operator object. The ConstraintsUnion logic operator succeeds if *at least* a single operand succeeds. The ConstraintsUnion object can be applied to any constraint and logic operator objects. The ConstraintsUnion object duck-types the immutable container object like Python :py:class:`tuple`. Parameters ---------- *constraints: Constraint or logic operator objects. Examples -------- .. code-block:: python class CapitalOrSmall(IA5String): ''' ASN.1 specification: CapitalOrSmall ::= IA5String (FROM ("A".."Z") | FROM ("a".."z")) ''' subtypeSpec = ConstraintsUnion( PermittedAlphabetConstraint('A', 'Z'), PermittedAlphabetConstraint('a', 'z') ) # this will succeed capital_or_small = CapitalAndSmall('Hello') # this will raise ValueConstraintError capital_or_small = CapitalOrSmall('hello!') """ def _testValue(self, value, idx): for constraint in self._values: try: constraint(value, idx) except error.ValueConstraintError: pass else: return raise error.ValueConstraintError( 'all of %s failed for "%s"' % (self._values, value) ) # TODO: # refactor InnerTypeConstraint # add tests for type check # implement other constraint types # make constraint validation easy to skip PK!窬舕 tagmap.pynu刐迭# # This file is part of pyasn1 software. # # Copyright (c) 2005-2020, Ilya Etingof # License: https://pyasn1.readthedocs.io/en/latest/license.html # from pyasn1 import error __all__ = ['TagMap'] class TagMap(object): """Map *TagSet* objects to ASN.1 types Create an object mapping *TagSet* object to ASN.1 type. *TagMap* objects are immutable and duck-type read-only Python :class:`dict` objects holding *TagSet* objects as keys and ASN.1 type objects as values. Parameters ---------- presentTypes: :py:class:`dict` Map of :class:`~pyasn1.type.tag.TagSet` to ASN.1 objects considered as being unconditionally present in the *TagMap*. skipTypes: :py:class:`dict` A collection of :class:`~pyasn1.type.tag.TagSet` objects considered as absent in the *TagMap* even when *defaultType* is present. defaultType: ASN.1 type object An ASN.1 type object callee *TagMap* returns for any *TagSet* key not present in *presentTypes* (unless given key is present in *skipTypes*). """ def __init__(self, presentTypes=None, skipTypes=None, defaultType=None): self.__presentTypes = presentTypes or {} self.__skipTypes = skipTypes or {} self.__defaultType = defaultType def __contains__(self, tagSet): return (tagSet in self.__presentTypes or self.__defaultType is not None and tagSet not in self.__skipTypes) def __getitem__(self, tagSet): try: return self.__presentTypes[tagSet] except KeyError: if self.__defaultType is None: raise elif tagSet in self.__skipTypes: raise error.PyAsn1Error('Key in negative map') else: return self.__defaultType def __iter__(self): return iter(self.__presentTypes) def __repr__(self): representation = '%s object' % self.__class__.__name__ if self.__presentTypes: representation += ', present %s' % repr(self.__presentTypes) if self.__skipTypes: representation += ', skip %s' % repr(self.__skipTypes) if self.__defaultType is not None: representation += ', default %s' % repr(self.__defaultType) return '<%s>' % representation @property def presentTypes(self): """Return *TagSet* to ASN.1 type map present in callee *TagMap*""" return self.__presentTypes @property def skipTypes(self): """Return *TagSet* collection unconditionally absent in callee *TagMap*""" return self.__skipTypes @property def defaultType(self): """Return default ASN.1 type being returned for any missing *TagSet*""" return self.__defaultType # Backward compatibility def getPosMap(self): return self.presentTypes def getNegMap(self): return self.skipTypes def getDef(self): return self.defaultType PK!鮏繲- - opentype.pynu刐迭# # This file is part of pyasn1 software. # # Copyright (c) 2005-2020, Ilya Etingof # License: https://pyasn1.readthedocs.io/en/latest/license.html # __all__ = ['OpenType'] class OpenType(object): """Create ASN.1 type map indexed by a value The *OpenType* object models an untyped field of a constructed ASN.1 type. In ASN.1 syntax it is usually represented by the `ANY DEFINED BY` for scalars or `SET OF ANY DEFINED BY`, `SEQUENCE OF ANY DEFINED BY` for container types clauses. Typically used together with :class:`~pyasn1.type.univ.Any` object. OpenType objects duck-type a read-only Python :class:`dict` objects, however the passed `typeMap` is not copied, but stored by reference. That means the user can manipulate `typeMap` at run time having this reflected on *OpenType* object behavior. The |OpenType| class models an untyped field of a constructed ASN.1 type. In ASN.1 syntax it is usually represented by the `ANY DEFINED BY` for scalars or `SET OF ANY DEFINED BY`, `SEQUENCE OF ANY DEFINED BY` for container types clauses. Typically used with :class:`~pyasn1.type.univ.Any` type. Parameters ---------- name: :py:class:`str` Field name typeMap: :py:class:`dict` A map of value->ASN.1 type. It's stored by reference and can be mutated later to register new mappings. Examples -------- For untyped scalars: .. code-block:: python openType = OpenType( 'id', {1: Integer(), 2: OctetString()} ) Sequence( componentType=NamedTypes( NamedType('id', Integer()), NamedType('blob', Any(), openType=openType) ) ) For untyped `SET OF` or `SEQUENCE OF` vectors: .. code-block:: python openType = OpenType( 'id', {1: Integer(), 2: OctetString()} ) Sequence( componentType=NamedTypes( NamedType('id', Integer()), NamedType('blob', SetOf(componentType=Any()), openType=openType) ) ) """ def __init__(self, name, typeMap=None): self.__name = name if typeMap is None: self.__typeMap = {} else: self.__typeMap = typeMap @property def name(self): return self.__name # Python dict protocol def values(self): return self.__typeMap.values() def keys(self): return self.__typeMap.keys() def items(self): return self.__typeMap.items() def __contains__(self, key): return key in self.__typeMap def __getitem__(self, key): return self.__typeMap[key] def __iter__(self): return iter(self.__typeMap) PK!捧钮"__pycache__/useful.cpython-311.pycnu刐迭 辤篝ddlZddlmZddlmZddlmZddlmZgdZejZej Z Gddej Z Gd d e Z Gd d eje ZGd deje ZdS)N)error)char)tag)univ)ObjectDescriptorGeneralizedTimeUTCTimec笫eZdZejjZejjej ej ej dZej Z dS)rN)__name__ __module__ __qualname__r GraphicString__doc__tagSet tagImplicitlyrTagtagClassUniversaltagFormatSimple getTypeIdtypeId鷕/builddir/build/BUILD/imunify360-venv-2.6.2/opt/imunify360/venv/lib/python3.11/site-packages/pyasn1/type/useful.pyrrse (G  & 4 4%爏':窤>>F   ) ) + +FFFrrc髣eZdZdZdZdZdZGddejZ e Z e dZ e dZdS) TimeMixInFc,eZdZdZd dZdZdZdZdS) TimeMixIn.FixedOffsetz&Fixed offset in minutes east from UTC.rUTCc驢tj||_||_dS)N)minutes)datetime timedelta_FixedOffset__offset_FixedOffset__name)selfoffsetnames r__init__zTimeMixIn.FixedOffset.__init__,s"$.皏>>>圖孧圖孠圞圞rc|jSN)r%r'dts r utcoffsetzTimeMixIn.FixedOffset.utcoffset0s = rc|jSr,)r&r-s rtznamezTimeMixIn.FixedOffset.tzname3s ; rc*tjdS)Nr)r#r$r-s rdstzTimeMixIn.FixedOffset.dst6s%燼(( (rN)rr )r r rrr*r/r1r3rrr FixedOffsetr's[44     ! ! !    ) ) ) ) )rr4c箨t|}|drtj}|dd}n d|vsd|vrd|vr|d\}}}n|d\}}}|jrt |dkr|dz }t |dkrtjd |z t|ddd zt|ddz}|dkr|dz}n%#t$rtjd |zwxYwt |d }nd}d |vsd|vrpd |vr|d \}}}n|d\}}} t|dz}n'#t$rtjd|zwxYwd}|j r!t ||j z dkr|dz }n t ||j z dkr|dz } tj||j dkrdpd}n%#t$rtjd|zwxYw|||S)z稢reate :py:class:`datetime.datetime` object from a |ASN.1| object. Returns ------- : new instance of :py:class:`datetime.datetime` object ZN-+00rzmalformed time zone offset %s<zunknown time specification %s?.,殍z$bad sub-second time specification %sr0000 %Y%m%d%H%M%S %y%m%d%H%M%Szmalformed datetime format %s) microsecondtzinfo)strendswithrr partition_shortTZlenr PyAsn1Errorint ValueErrorr4_optionalMinutes _yearsDigitsr#strptimereplace) r'textrG plusminustzr"_msr.s r asDateTimezTimeMixIn.asDateTime;s4墆寉 ==   擼團9圖塂 怐圼圼楥4楰橩恉坽坽&*癝&9&9#恑&*癝&9&9#恑寎 燫ˋ恉 2墂寃!妡坾'(G"(LMMM P榖!渇++*璖癆癇癇琜8##榬慚怗 P P P'(G$(NOOO P**7癈88團團團 $;;#++恉坽坽"焠歯⊿11 恆"焠歯⊿11 恆 W慦擶榯慯 W W W'(N蠶U(UVVV W圔   1B%B繿%G%G 怓塏圖圖 塝孻* *╝ / / 怐塋圖 K"++―$2C纐2H2[萟2m衉mnn圔圔 K K K#$B繲$IJJ J K弞妟燽坺888s$=D"D'F"F= -H99"Ic2||jdkrdpd}|jr|d|jdzzz }|r;|j}|dkr|dz }n|dz }|d |d z|d zfzz }n|d z }||S) aUCreate |ASN.1| object from a :py:class:`datetime.datetime` object. Parameters ---------- dt: :py:class:`datetime.datetime` object The `datetime.datetime` object to initialize the |ASN.1| object from Returns ------- : new instance of |ASN.1| value rrDrEz.%dr@rr8r9z%.2d%.2dir6)strftimerQ _hasSubsecondrFr/seconds)clsr.rTr]s r fromDateTimezTimeMixIn.fromDateTime~s弡妠3+╭0C癪U纞VV   5 怑楻淾╰34 4圖 <<>> 條抣憂攏,圙妠坽   怞'═/7窽>!BB B圖圖 怌塊圖坰4墆寉rN)r r rrQr\rPrKr#rGr4r propertyrY classmethodr_rrrrr sLMH)))))恏攐)))$ +--C @9@9刋@9餌刐rrc筅eZdZejjZejjej ej ej dZej ZdZdZdZdZdS)rrTNr r rr VisibleStringrrrrrrrVideotexStringrrrQr\rPrKrrrrrsz (G  & 4 4%爏':窧??F  * * , ,FLMHHHrrc筅eZdZejjZejjej ej ej dZej ZdZdZdZdZdS)r r:FNrdrrrr r sz (G  & 4 4%爏':窧??F  * * , ,FLMHHHrr )r#pyasn1r pyasn1.typerrr__all__NoValuenoValuerrobjectrrerr rrrros9 < < < , , , , , , ,恡) , , ,{{{{{{{{饇恉()"坉 )rPK!'Κ&& __pycache__/univ.cpython-311.pycnu刐迭 辤湭篝ddlZddlZddlmZddlmZddlmZddlm Z ddlm Z ddlm Z ddlm Z dd lm Z dd lmZe jZeZgd ZGd d e jZGddeZGddeZGdde jZGdde jZGddeZGdde jZGdde jZGdde jZGddeZGd d!e jZGd"d#eZ Gd$d%eZ!Gd&d'e jZ"Gd(d)e"Z#Gd*d+e"Z$Gd,d-e$Z%Gd.d/eZ&dS)0N)error)eoo)integer)base) constraint) namedtype)namedval)tag)tagmap)IntegerBoolean BitString OctetStringNullObjectIdentifierReal EnumeratedSequenceOfAndSetOfBase SequenceOfSetOfSequenceAndSetBaseSequenceSetChoiceAnyNoValuenoValueceZdZdZejejejejdZ e j Z e jZejZefdZdZdZdZdZdZd Zd Zd Zd Zd ZdZ dZ!dZ"dZ#dZ$dZ%d2dZ&dZ'dZ(dZ)dZ*dZ+dZ,dZ-ejj.Z.dZ/dZ0dZ1d Z2d!Z3d"Z4d#Z5d3d%Z6d&Z7d'Z8d(Z9d)Z:d*Z;d+Zd.Z?d/Z@d0ZAd1ZBdS)4r aCreate |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.SimpleAsn1Type`, its objects are immutable and duck-type Python :class:`int` objects. Keyword Args ------------ value: :class:`int`, :class:`str` or |ASN.1| object Python :class:`int` or :class:`str` literal or |ASN.1| class instance. If `value` is not given, schema object will be created. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s). Constraints verification for |ASN.1| type occurs automatically on object instantiation. namedValues: :py:class:`~pyasn1.type.namedval.NamedValues` Object representing non-default symbolic aliases for numbers Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer. Examples -------- .. code-block:: python class ErrorCode(Integer): ''' ASN.1 specification: ErrorCode ::= INTEGER { disk-full(1), no-disk(-1), disk-not-formatted(2) } error ErrorCode ::= disk-full ''' namedValues = NamedValues( ('disk-full', 1), ('no-disk', -1), ('disk-not-formatted', 2) ) error = ErrorCode('disk-full') c 驲d|vr |j|d<tjj||fi|dS)N namedValues)r!rSimpleAsn1Type__init__selfvaluekwargss 鷓/builddir/build/BUILD/imunify360-venv-2.6.2/opt/imunify360/venv/lib/python3.11/site-packages/pyasn1/type/univ.pyr#zInteger.__init__es>  & &$($4團= ! $燭5;;癋;;;;;c<||j|zSNclone_valuer%r&s r(__and__zInteger.__and__k弞妟$+-...r)c<|||jzSr+r,r/s r(__rand__zInteger.__rand__n弞妟%$+-...r)c<||j|zSr+r,r/s r(__or__zInteger.__or__qr1r)c<|||jzSr+r,r/s r(__ror__zInteger.__ror__tr4r)c<||j|z Sr+r,r/s r(__xor__zInteger.__xor__wr1r)c<|||jz Sr+r,r/s r(__rxor__zInteger.__rxor__zr4r)c<||j|zSr+r,r/s r( __lshift__zInteger.__lshift__}弞妟$+.///r)c<||j|z Sr+r,r/s r( __rshift__zInteger.__rshift__r?r)c<||j|zSr+r,r/s r(__add__zInteger.__add__r1r)c<|||jzSr+r,r/s r(__radd__zInteger.__radd__r4r)c<||j|z Sr+r,r/s r(__sub__zInteger.__sub__r1r)c<|||jz Sr+r,r/s r(__rsub__zInteger.__rsub__r4r)c<||j|zSr+r,r/s r(__mul__zInteger.__mul__r1r)c<|||jzSr+r,r/s r(__rmul__zInteger.__rmul__r4r)c<||j|zSr+r,r/s r(__mod__zInteger.__mod__r1r)c<|||jzSr+r,r/s r(__rmod__zInteger.__rmod__r4r)Nc骉|t|j||Sr+r-powr.r%r&modulos r(__pow__zInteger.__pow__s"弞妟#榙渒5&99:::r)c驲|t||jSr+rSr/s r(__rpow__zInteger.__rpow__s 弞妟#榚燭11222r)c<||j|zSr+r,r/s r( __floordiv__zInteger.__floordiv__r?r)c<|||jzSr+r,r/s r( __rfloordiv__zInteger.__rfloordiv__s弞妟%4;.///r)c0t|j|z Sr+rr.r/s r( __truediv__zInteger.__truediv__s怐擪%'(((r)c0t||jz Sr+r_r/s r( __rtruediv__zInteger.__rtruediv__s怑楧淜'(((r)c驲|t|j|Sr+r-divmodr.r/s r( __divmod__zInteger.__divmod__s 弞妟&╡44555r)c驲|t||jSr+rdr/s r( __rdivmod__zInteger.__rdivmod__s 弞妟& 44555r)c*t|jSr+intr.r%s r(__int__zInteger.__int__4;r)c*t|jSr+floatr.rls r( __float__zInteger.__float__怲擺!!!r)c驪|t|jSr+)r-absr.rls r(__abs__zInteger.__abs__s弞妟#榙渒**+++r)c*t|jSr+rjrls r( __index__zInteger.__index__rnr)c8||j Sr+r,rls r(__pos__zInteger.__pos__弞妟4;,'''r)c8||j Sr+r,rls r(__neg__zInteger.__neg__r{r)c8||jSr+r,rls r( __invert__zInteger.__invert__r{r)rc骬t|j|}|r||S|Sr+)roundr.r-r%nrs r( __round__zInteger.__round__s0 $+榪 ! !  ::榓== 圚r)c4tj|jSr+)mathfloorr.rls r( __floor__zInteger.__floor__s寊$+&&&r)c4tj|jSr+)rceilr.rls r(__ceil__zInteger.__ceil__s寉%%%r)c骦|tj|jSr+)r-rtruncr.rls r( __trunc__zInteger.__trunc__s 弞妟$*燭11222r)c|j|kSr+r.r/s r(__lt__zInteger.__lt__寋楿""r)c|j|kSr+rr/s r(__le__zInteger.__le__寋榚##r)c|j|kSr+rr/s r(__eq__zInteger.__eq__rr)c|j|kSr+rr/s r(__ne__zInteger.__ne__rr)c|j|kSr+rr/s r(__gt__zInteger.__gt__rr)c|j|kSr+rr/s r(__ge__zInteger.__ge__rr)c蠖 t|S#t$r= |j|cYS#t$r}t jd|d|d}~wwxYwwxYw)Nz Can't coerce z into integer: )rk ValueErrorr!KeyErrorr PyAsn1Errorr%r&excs r(prettyInzInteger.prettyIns 恥::     '....   '';@򌮇##F   鴖( A +A AAAAc髒 t|j|S#t$rt|cYSwxYwr+)strr!rr/s r( prettyOutzInteger.prettyOutsJ 恡'.// /   恥::    鴖 88c|jSr+r!rls r(getNamedValueszInteger.getNamedValuess r)r+r)C__name__ __module__ __qualname____doc__r initTagSetTagtagClassUniversaltagFormatSimpletagSetrConstraintsIntersection subtypeSpecr NamedValuesr!rr" getTypeIdtypeIdrr#r0r3r6r8r:r<r>rArCrErGrIrKrMrOrQrWrYr[r]r`rbrfrh__hash__rmrrrvrxrzr}rrrrrrrrrrrrrrr)r(r r sI00餳圫宆%爏':窪AAF5*466K'(&((K * * , ,F$<<<< //////////////////000000////////////////////////;;;;333000000))))))666666"+H   """,,,   ((((((((('''&&&333###$$$$$$$$$###$$$        r)r c筲eZdZdZejejejejdZ e j e j ddzZ ejddZe ZdS)r adCreate |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.SimpleAsn1Type`, its objects are immutable and duck-type Python :class:`int` objects. Keyword Args ------------ value: :class:`int`, :class:`str` or |ASN.1| object Python :class:`int` or :class:`str` literal or |ASN.1| class instance. If `value` is not given, schema object will be created. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s).Constraints verification for |ASN.1| type occurs automatically on object instantiation. namedValues: :py:class:`~pyasn1.type.namedval.NamedValues` Object representing non-default symbolic aliases for numbers Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer. Examples -------- .. code-block:: python class RoundResult(Boolean): ''' ASN.1 specification: RoundResult ::= BOOLEAN ok RoundResult ::= TRUE ko RoundResult ::= FALSE ''' ok = RoundResult(True) ko = RoundResult(False) r)Falser)TruerN)rrrrr rrrrrr rrSingleValueConstraintr rr!rrrr)r(r r s**餦圫宆%爏':窪AAF%(H (H華(N(NNK'(&爘癧AAK   FFFr)r c"eZdZdxZZdZdZdS) SizedIntegerNc骽||_t||z d|_|SNr) bitLengthmax bit_lengthleadingZeroBits)r%rs r( setBitLengthzSizedInteger.setBitLengthIs/""9╰/@/@#@!DD r)c髄|j'|||jSr+)rrrrls r(__len__zSizedInteger.__len__Ns0 > !   榙無歰// 0 0 0寏r))rrrrrrrrr)r(rrFs<"&&I r)rc缶eZdZdZejejejejdZ e j Z e jZejZexZZefdZdZdZdZdZdZd Zd Zd Zd Z d Z!dZ"dZ#dZ$dZ%dZ&dZ'dZ(dZ)dZ*dZ+dZ,dZ-dZ.e/d"dZ0e/d"dZ1e/d#d Z2d!Z3dS)$raCreate |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.SimpleAsn1Type`, its objects are immutable and duck-type both Python :class:`tuple` (as a tuple of bits) and :class:`int` objects. Keyword Args ------------ value: :class:`int`, :class:`str` or |ASN.1| object Python :class:`int` or :class:`str` literal representing binary or hexadecimal number or sequence of integer bits or |ASN.1| object. If `value` is not given, schema object will be created. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s). Constraints verification for |ASN.1| type occurs automatically on object instantiation. namedValues: :py:class:`~pyasn1.type.namedval.NamedValues` Object representing non-default symbolic aliases for numbers binValue: :py:class:`str` Binary string initializer to use instead of the *value*. Example: '10110011'. hexValue: :py:class:`str` Hexadecimal string initializer to use instead of the *value*. Example: 'DEADBEEF'. Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer. Examples -------- .. code-block:: python class Rights(BitString): ''' ASN.1 specification: Rights ::= BIT STRING { user-read(0), user-write(1), group-read(2), group-write(3), other-read(4), other-write(5) } group1 Rights ::= { group-read, group-write } group2 Rights ::= '0011'B group3 Rights ::= '3'H ''' namedValues = NamedValues( ('user-read', 0), ('user-write', 1), ('group-read', 2), ('group-write', 3), ('other-read', 4), ('other-write', 5) ) group1 = Rights(('group-read', 'group-write')) group2 = Rights('0011') group3 = Rights(0x3) c |turz|rx ||dd}n#t$rYnwxYw ||dd}n#t$rYnwxYw|turU|jtur||jd}n*|jtur||jd}d|vr |j|d<tj j ||fi|dS)NbinValueTinternalFormathexValuer!) rfromBinaryStringpopr fromHexStringdefaultBinValuedefaultHexValuer!rr"r#r$s r(r#zBitString.__init__sL 旼    11&**竄2H2H衁]1^^怑怑怐 ..╲痾獄*/E/E蠽Z.[[怑怑怐 旼  #722--╠.B蠸W-XX%璚44**4+?蠵T*UU  & &$($4團= ! $燭5;;癋;;;;;s!*8 AA *A44 BBc*|Sr+)asBinaryrls r(__str__zBitString.__str__s弣妢r)c髷||}||up/|j|ko$t|jt|kSr+rr.lenr%others r(rzBitString.__eq__sD 榚$$恥坿W ╱ 4 W窽糩9I9I蚐蠶V蒢蘘9WWr)c髮||}|j|kp$t|jt|kSr+rrs r(rzBitString.__ne__s: 榚$$寋榚#E4;'7'73竨::'EEr)c笾||}t|jt|kp/t|jt|ko |j|kSr+rrr.rs r(rzBitString.__lt__骔 榚$$4;#爀**,f癉碖0@0@臗罦腏0N0f蠸W許^衋f襍ffr)c笾||}t|jt|kp/t|jt|ko |j|kSr+rrs r(rzBitString.__le__骔 榚$$4;3爑::-h癟碵1A1A臩罿腪1O1h蠺X訲_衏h襎hhr)c笾||}t|jt|kp/t|jt|ko |j|kSr+rrs r(rzBitString.__gt__rr)c笾||}t|jt|kp/t|jt|ko |j|kSr+rrs r(rzBitString.__ge__rr)c*t|jSr+rr.rls r(rzBitString.__len__rnr)c 4|jturHfdt|t DSt jdz }||ks|dkrtdj||z z dzS)Nc g|] }| Srr).0xr%s r( z)BitString.__getitem__..s鴢MMM1榯燗渨MMMr)rrzbit index out of range) __class__slicer-rangeindicesrr. IndexError)r%ilengths` r( __getitem__zBitString.__getitem__s鴢 ;%  ::MMMM皅穣瞴繲7K7K0LMMMNN N%%)團6妟坺楺歎楿 !9:::擪燜≦/14 4r)c#骹Kt|j}|r|dz}|j|z dzV|dSdSNrr)r%rs r(__iter__zBitString.__iter__s\怲擺!! . 恆塊團;&(ˋ- - - - . . . . .r)c:tt|Sr+)reversedtuplerls r( __reversed__zBitString.__reversed__s榙 $$$r)c ||}|t|jt |z|zt |jt |zSr+)rr-rr.rrr/s r(rCzBitString.__add__si 榚$$弞妟,爐礳%眏磈'@5'HIIVV誛Z衃_訹f裌g訵g誮m衝s裫t詊t裌tuuvvvr)c||}|t|t|jz|jzt|jt|zSr+)rr-rrr.rr/s r(rEzBitString.__radd__sm 榚$$弞妟,爑癉碖0@0@'@4;'NOO\\誡`衋e詀l裖m註m誴s衪y裵z詐z裖z{{|||r)c鬄|j}|dkr,|t|jz}||jz}|dz}|dk,||Sr)r.rr-)r%r& bitStrings r(rKzBitString.__mul__sZ擪 恆奿坕 #榙渒** *圛  $圛 怮塉圗恆奿坕弞妟)$$$r)c ||zSr+rr/s r(rMzBitString.__rmul__  恊墊r)c螃|t|j|zt |j|zSr+)r-rr.rrr%counts r(r>zBitString.__lshift__ sA弞妟,爐癳';<<II#萪蘫袹Z訨Z衇b袹bccdddr)c 舐|t|j|z t dt |j|z Sr)r-rr.rrrrs r(rAzBitString.__rshift__sN弞妟,爐癳';<<II#萢誕T蠻Y訳`裃a訯a衐i裃i袹j訨jkklllr)c*t|jSr+rjrls r(rmzBitString.__int__rnr)c*t|jSr+rprls r(rrzBitString.__float__rsr)c驞t|S)zet |ASN.1| value as a sequence of 8-bit integers. If |ASN.1| object length is not a multiple of 8, result will be left-padded with zeros. )rasOctetsrls r( asNumberszBitString.asNumberss 怲梋抅慱擾%%%r)c驲tj|jt|S)z淕et |ASN.1| value as a sequence of octets. If |ASN.1| object length is not a multiple of 8, result will be left-padded with zeros. )r)rto_bytesr.rrls r(r zBitString.asOctets s"  礐盜碔>>>>r)c|jS)z5Get |ASN.1| value as a single integer value. rrls r( asIntegerzBitString.asInteger(s 寋r)c髱t|jdd}dt|jt|z z|zS)z4Get |ASN.1| value as a text string of bits. rN0)binr.r)r% binStrings r(rzBitString.asBinary-sA $$燪燫燫( 昪$+&&╕789DDr)FNc蟋 t|dt|dz}n0#t$r#}t j|jd|d}~wwxYw|乢tt|t|z|zt|t|z}|s ||}|S)Create a |ASN.1| object initialized from the hex string. Parameters ---------- value: :class:`str` Text string like 'DEADBEEF' z.fromHexString() error: Nrrrrrrrclsr&rprependrs r(rzBitString.fromHexString3s Z ++88窾繿HH圗圗 Z Z Z#纁膌纋纋蠺W蠺W$XYY Y Z   榞&&#╡**4=妉3榳<<#╡**455  怌慗擩圗 s36 A#AA#c螵 t|pddt|}n0#t$r#}t j|jd|d}~wwxYw|乢tt|t|z|zt|t|z}|s ||}|S)Create a |ASN.1| object initialized from a string of '0' and '1'. Parameters ---------- value: :class:`str` Text string like '1010111' rrz.fromBinaryString() error: Nrrs r(rzBitString.fromBinaryStringLs ] #╭11>>絪5箊紌JJ圗圗 ] ] ]#蠾Z蠾Z$[\\ \ ]   榞&&#╡**4=妉3榳<<#╡**455  怌慗擩圗 s25 A"AA"rc鬄ttt|d|z t |dz|z }|乢tt|t |z|zt |t |z}|s ||}|S)z獵reate a |ASN.1| object initialized from a string. Parameters ---------- value: :class:`bytes` Text string like b'\\x01\\xff' big)rrk from_bytesbytesrr)rr&rrpaddings r(fromOctetStringzBitString.fromOctetStringes漇焇歗璄%㎜琇%@@繥KLLYY語]衈c裐d訸d術h裐h衚r裐rss   榞&&#╡**4=妉3榳<<#╡**455  怌慗擩圗 r)c蟥t|tr|St|tr諀s"tddS|ddkrq|dddkr|dddS|dddkr|dddSt jd |jr畖 s歞 | d D} fd |D}n%#t$rt jd |wxYwt|}d}|D] }|d||z zz}t||dzS| dr|dddS| dr|dddS|dSt|ttfr4dd|DdSt|t"r/t|t%|St|t&rt|St jd|d)Nr'辋z'BrTrz'HzBad BIT STRING value notation c6g|]}|Sr)striprrs r(rz&BitString.prettyIn..s ===爍===r),c*g|]}j|Srr)rnamer%s r(rz&BitString.prettyIn..s!鴢#M#M#M竧燚$4癟$:#M#M#Mr)zunknown bit name(s) in 0xr0bcg|]}|rdpd S)1rr)rbs r(rz&BitString.prettyIn..s!1R1R1R纐!)2B竤1R1R1Rr)z Bad BitString initializer type ') isinstancerrrrrrrr!isdigitsplitrr startswithrlistjoinrrrk)r%r&names bitPositionsrightmostPositionnumber bitPositions` r(rzBitString.prettyInzs)鴢 恊漒 * *7 圠 漵 # #5 & I#燗33癆666恞楾!!:&&00皅皌萒0RRR𩒁3擹5((--╡癆癰癉琸$-OOO++>C竐E! I%--// I==‥疜狵,<,<===T#M#M#M#M纔#M#M#M怢怢TTT++򽾧,RSSST%( $5$5!#/EE怟榓$5 $CDD怓怓#燜++889J萉9NOOO!!$'' I))%)繢)III!!$'' I,,║񲷄2琘纓,LLL,,║4,HHH 榼 - - ((1R1R菶1R1R1R)S)S衐h(ii i 漼 ) ) &&33礐盝碕?? ? 漵 # # && &##;@򌮇B s D"D<)FN)FNr)4rrrrr rrrrrrrrr rr!rr"rrrrrr#rrrrrrrrrrrrCrErKrMr>rArmrrr r rr classmethodrrr&rrr)r(rrUs>>餌圫宆%爏':窪AAF5*466K'(&((K * * , ,F(//O恛$<<<<6XXXFFFgggiiigggiii    555... %%% www}}}%%%eeemmm   """&&&??? EEE 刐0刐0刐(88888r)rc骹eZdZdZejejejejdZ e j Z e jZexZZdZefdZdZdZdZdZd Zd Zdd Zed ZedZdZ dZ!dZ"dZ#dZ$dZ%dZ&dZ'dZ(dZ)dZ*dS)raCreate |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.SimpleAsn1Type`, its objects are immutable and duck-type :class:`bytes`. When used in Unicode context, |ASN.1| type assumes "|encoding|" serialisation. Keyword Args ------------ value: :class:`unicode`, :class:`str`, :class:`bytes` or |ASN.1| object :class:`bytes`, alternatively :class:`str` representing character string to be serialised into octets (note `encoding` parameter) or |ASN.1| object. If `value` is not given, schema object will be created. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s). Constraints verification for |ASN.1| type occurs automatically on object instantiation. encoding: :py:class:`str` Unicode codec ID to encode/decode :class:`str` the payload when |ASN.1| object is used in text string context. binValue: :py:class:`str` Binary string initializer to use instead of the *value*. Example: '10110011'. hexValue: :py:class:`str` Hexadecimal string initializer to use instead of the *value*. Example: 'DEADBEEF'. Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer. Examples -------- .. code-block:: python class Icon(OctetString): ''' ASN.1 specification: Icon ::= OCTET STRING icon1 Icon ::= '001100010011001000110011'B icon2 Icon ::= '313233'H ''' icon1 = Icon.fromBinaryString('001100010011001000110011') icon2 = Icon.fromHexString('313233') rz iso-8859-1c |r}|turt ||d}n#t$rYnwxYw ||d}n#t$rYnwxYw|turQ|jtur||j}n(|jtur||j}d|vr |j|d<tj j ||fi|dS)Nrrencoding) rrrrrrrrDrr"r#r$s r(r#zOctetString.__init__s3   11&**竄2H2HII怑怑怐 ..╲痾獄*/E/EFF怑怑怐 旼  #722--╠.BCC%璚44**4+?@@ 榁 # #!%團:  $燭5;;癋;;;;;s!(6 AA(A00 A=<A=c骦t|tr|St|trN ||jS#t $r&}t jd|d|jd|d}~wwxYwt|tr| St|tj r"| t|St|ttfr"| t|St|S)NzCan't encode string '' with 'z' codec)r6r$rencoderDUnicodeEncodeErrorrPyAsn1UnicodeEncodeErrorrr rr"rrr:rs r(rzOctetString.prettyIns 恊漊 # # 圠 漵 # #  梶抾燚222%   44$榰榰燿爉爉569  漿 + + >>## # 漷2 3 3 ==燯,, , 榼 - - ==爑.. .<< sA A8!A33A8c 筇 |j|jS#t$r8}t jd|jd|jd|jjd|d}~wwxYw)NzCan't decode string 'rFz ' codec at 'r()r.decoderDUnicodeDecodeErrorrPyAsn1UnicodeDecodeErrorrr)r%rs r(rzOctetString.__str__5s} ;%%燿44 4!   00+++爐爙爙 淣333569  鴖! A#3AA#c*t|jSr+r$r.rls r( __bytes__zOctetString.__bytes__@rsr)c*t|jSr+rOrls r(r zOctetString.asOctetsCrsr)c*t|jSr+)rr.rls r(r zOctetString.asNumbersFrsr)c|Sr+rr/s r(rzOctetString.prettyOut[s r)rc||j}||jur|S|}|D]2}|dks|dkr$ddd|DzcS3t|S)N 閪r0r2c3 K|] }d|zV dS)z%.2xNrr,s r( z*OctetString.prettyPrint..js&&C&C癮爒&C&C&C&C&C&Cr))rr.r r;rr)r%scoper&numbersrs r( prettyPrintzOctetString.prettyPrint^s榯渰++  # #圠.."" - -圓2妚坴楽榖焔歡&C&C7&C&C&CDDDDDD!&&爐,, ,r)cd}d}g}|D]V}|r|dz}nd}||d}|dvrt|}ntjd||||zz}學||t |S)rr"rr)rr4z$Non-binary OCTET STRING initializer )appendrkrrr$)r&bitNobytervs r(rzOctetString.fromBinaryStringos   圓  怞慒擣''谸AC 怉慗 圖圖 怮墄寈r)c筌g}g}|D]/}|r)|t||zdd}-|}0|r&|t|dzdt|S)rrNr)r^rkr$)r&rpras r(rzOctetString.fromHexStrings    圓 楺橴燘(((  ' 廐奌昐楽"%% & & &怮墄寈r)c*t|jSr+rrls r(rzOctetString.__len__rnr)c髕|jtur ||j|S|j|Sr+rrr-r.r%rs r(rzOctetString.__getitem__3 ;%  ::榙渒!渘-- -;榪> !r)c*t|jSr+iterr.rls r(rzOctetString.__iter__怐擪   r)c||jvSr+rr/s r( __contains__zOctetString.__contains__ ##r)c骲||j||zSr+)r-r.rr/s r(rCzOctetString.__add__s'弞妟$+ 癳(<(<<===r)c骲||||jzSr+)r-rr.r/s r(rEzOctetString.__radd__s'弞妟$--..<===r)c<||j|zSr+r,r/s r(rKzOctetString.__mul__r1r)c ||zSr+rr/s r(rMzOctetString.__rmul__rr)c*t|jSr+rjrls r(rmzOctetString.__int__rnr)c*t|jSr+rprls r(rrzOctetString.__float__rsr)c*t|jSr+)rr.rls r(rzOctetString.__reversed__s $$$r)Nr)+rrrrr rrrrrrrrrr"rrrrrrDr#rrrPr r rr[ staticmethodrrrrrrnrCrErKrMrmrrrrr)r(rrs88饃圫宆%爏':窪AAF5*466K * * , ,F(//O恛H$<<<<6   2   """""""""*----"刓<刓.   """ !!!$$$>>>>>>///   """%%%%%r)rc竽eZdZdZejejejejdZ e j e j dzZ e ZdZdS)raiCreate |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.SimpleAsn1Type`, its objects are immutable and duck-type Python :class:`str` objects (always empty). Keyword Args ------------ value: :class:`str` or |ASN.1| object Python empty :class:`str` literal or any object that evaluates to :obj:`False` If `value` is not given, schema object will be created. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer. Examples -------- .. code-block:: python class Ack(Null): ''' ASN.1 specification: Ack ::= NULL ''' ack = Ack('') r)c|r|SdS)Nr)rr/s r(rz Null.prettyIns  圠坰r)N)rrrrr rrrrrrrrrrrrrr)r(rrs餒圫宆%爏':窪AAF),L↗,L萐,Q,QQK " " $ $Fr)rc篪eZdZdZejejejejdZ e j Z e jZdZdZdZdZdZdZd Zd Zd Zd Zd ZdS)ra5Create |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.SimpleAsn1Type`, its objects are immutable and duck-type Python :class:`tuple` objects (tuple of non-negative integers). Keyword Args ------------ value: :class:`tuple`, :class:`str` or |ASN.1| object Python sequence of :class:`int` or :class:`str` literal or |ASN.1| object. If `value` is not given, schema object will be created. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s). Constraints verification for |ASN.1| type occurs automatically on object instantiation. Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer. Examples -------- .. code-block:: python class ID(ObjectIdentifier): ''' ASN.1 specification: ID ::= OBJECT IDENTIFIER id-edims ID ::= { joint-iso-itu-t mhs-motif(6) edims(7) } id-bp ID ::= { id-edims 11 } ''' id_edims = ID('2.6.7') id_bp = id_edims + (11,) c<||j|zSr+r,rs r(rCzObjectIdentifier.__add__8r1r)c<|||jzSr+r,rs r(rEzObjectIdentifier.__radd__;r4r)c|jSr+rrls r(asTuplezObjectIdentifier.asTuple> 寋r)c*t|jSr+rrls r(rzObjectIdentifier.__len__Crnr)c髕|jtur ||j|S|j|Sr+rfrgs r(rzObjectIdentifier.__getitem__Frhr)c*t|jSr+rjrls r(rzObjectIdentifier.__iter__Lrlr)c||jvSr+rr/s r(rnzObjectIdentifier.__contains__Oror)c6|j|Sr+r.indexr%suboids r(rzObjectIdentifier.indexR寋  (((r)c髣t|}|t|kr|jd||d|krdSdS)arIndicate if this |ASN.1| object is a prefix of other |ASN.1| object. Parameters ---------- other: |ASN.1| object |ASN.1| object Returns ------- : :class:`bool` :obj:`True` if this |ASN.1| object is a parent (e.g. prefix) of the other |ASN.1| object or :obj:`False` otherwise. NTFrr%rls r( isPrefixOfzObjectIdentifier.isPrefixOfUsE 塈孖 怑 ??寋2楢2%)++恡坲r)c t|trt|St|tr╠|vr>t jd|d|jjdtj d td| dDS#t$r,}t jd|d|jjd|d}~wwxYw td|D}n@#ttf$r,}t jd|d|jjd|d}~wwxYwt|t|kr|St jd|d|jj) N-zMalformed Object ID  at : rc0g|]}|t|SrrkrsubOids r(rz-ObjectIdentifier.prettyIn..s#SSS╢菷S漜&檏渒SSSr).c8g|]}|dkt|Srrrs r(rz-ObjectIdentifier.prettyIn..z# P P P繤萢翶繩燰繩繩繩r))r6rrrrrrrsysexc_infor8r TypeErrorrr%r&r tupleOfIntss r(rzObjectIdentifier.prettyInis 恊- . . <<  漵 # # 恊坾坾'':?%%訟X蠥X蠥X語]訸f裐h訸h衖j訸k衂kl SS 繡8H8HSSSTTT   '':?%%訟X蠥X蠥X衂]衂]^    P P5 P P PQQ圞圞滻&   ##6;癳癳窽糬=T=T=T蠽Y蠽YZ   坽  漵5檢渮 ) ) %%%訧`蠭` abbb0=+B)) C3'CC#C==D:'D55D:c驚dd|DS)Nrc,g|]}t|Srrr,s r(rz.ObjectIdentifier.prettyOut..///燗楺///r)r;r/s r(rzObjectIdentifier.prettyOut#弜妜/////000r)Nrrrrr rrrrrrrrrr"rrrCrErrrrrnrrrrrr)r(rrs((餢圫宆%爏':窪AAF5*466K * * , ,F//////    """ !!!$$$)))(ccc:11111r)rc篪eZdZdZejejejejdZ e j Z e jZdZdZdZdZdZdZd Zd Zd Zd Zd ZdS) RelativeOIDa[Create |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.SimpleAsn1Type`, its objects are immutable and duck-type Python :class:`tuple` objects (tuple of non-negative integers). Keyword Args ------------ value: :class:`tuple`, :class:`str` or |ASN.1| object Python sequence of :class:`int` or :class:`str` literal or |ASN.1| object. If `value` is not given, schema object will be created. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s). Constraints verification for |ASN.1| type occurs automatically on object instantiation. Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer. Examples -------- .. code-block:: python class RelOID(RelativeOID): ''' ASN.1 specification: id-pad-null RELATIVE-OID ::= { 0 } id-pad-once RELATIVE-OID ::= { 5 6 } id-pad-twice RELATIVE-OID ::= { 5 6 7 } ''' id_pad_null = RelOID('0') id_pad_once = RelOID('5.6') id_pad_twice = id_pad_once + (7,) c<||j|zSr+r,rs r(rCzRelativeOID.__add__r1r)c<|||jzSr+r,rs r(rEzRelativeOID.__radd__r4r)c|jSr+rrls r(rzRelativeOID.asTuplerr)c*t|jSr+rrls r(rzRelativeOID.__len__rnr)c髕|jtur ||j|S|j|Sr+rfrgs r(rzRelativeOID.__getitem__rhr)c*t|jSr+rjrls r(rzRelativeOID.__iter__rlr)c||jvSr+rr/s r(rnzRelativeOID.__contains__ror)c6|j|Sr+rrs r(rzRelativeOID.indexrr)c髣t|}|t|kr|jd||d|krdSdS)apIndicate if this |ASN.1| object is a prefix of other |ASN.1| object. Parameters ---------- other: |ASN.1| object |ASN.1| object Returns ------- : :class:`bool` :obj:`True` if this |ASN.1| object is a parent (e.g. prefix) of the other |ASN.1| object or :obj:`False` otherwise. NTFrrs r(rzRelativeOID.isPrefixOfsE 塈孖 怑 ??寋2楢2%)++恡坲r)c t|trt|St|tr╠|vr>t jd|d|jjdtj d td| dDS#t$r,}t jd|d|jjd|d}~wwxYw td|D}n@#ttf$r,}t jd|d|jjd|d}~wwxYwt|t|kr|St jd|d|jj) NrzMalformed RELATIVE-OID rrrc0g|]}|t|Srrrs r(rz(RelativeOID.prettyIn..rr)rc8g|]}|dkt|Srrrs r(rz(RelativeOID.prettyIn..rr))r6rrrrrrrrrr8rrrrs r(rzRelativeOID.prettyIns 恊漑 ) ) <<  漵 # # 恊坾坾''=B窾窾繢腘訢[蠨[蠨[誡`註i裖k註k衛m註n衇no SS 繡8H8HSSSTTT   ''=B窾窾繢腘訢[蠨[蠨[衇`衇`a    P P5 P P PQQ圞圞滻&   ##9>訞W蠤W蠤W衁\衁\]   坽  漵5檢渮 ) ) 繳繳繳菵蘊訪c蠰c deeerc驚dd|DS)Nrc,g|]}t|Srrr,s r(rz)RelativeOID.prettyOut..rr)rr/s r(rzRelativeOID.prettyOutrr)Nrrr)r(rrs  餒圫宆%爏':窪AAF5*466K * * , ,F//////    """ !!!$$$)))$fff:11111r)rc骲eZdZdZdZ edZedZeefZn#e $r dxZZdZYnwxYwe j e j e j e jdZejZejZedZdZd0d Zed Zed Zed ZdZdZ dZ!dZ"dZ#dZ$dZ%dZ&d1dZ'dZ(dZ)dZ*dZ+dZ,dZ-dZ.dZ/dZ0d Z1d0d!Z2d"Z3d#Z4d$Z5d%Z6d&Z7d'Z8d(Z9d)Z:d*Z;d+Zd-Z?d.Z@d/ZAdS)2rabCreate |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.SimpleAsn1Type`, its objects are immutable and duck-type Python :class:`float` objects. Additionally, |ASN.1| objects behave like a :class:`tuple` in which case its elements are mantissa, base and exponent. Keyword Args ------------ value: :class:`tuple`, :class:`float` or |ASN.1| object Python sequence of :class:`int` (representing mantissa, base and exponent) or :class:`float` instance or |ASN.1| object. If `value` is not given, schema object will be created. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s). Constraints verification for |ASN.1| type occurs automatically on object instantiation. Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer. Examples -------- .. code-block:: python class Pi(Real): ''' ASN.1 specification: Pi ::= REAL pi Pi ::= { mantissa 314159, base 10, exponent -5 } ''' pi = Pi((314159, 10, -5)) Ninfz-infr c骕|\}}}|r|dzdkr|dz}|dz }|r |dzdk|||fS)N rrr)r&mr5es r(__normalizeBase10zReal.__normalizeBase10QsV1坅 怉慒榓扠怟 塆圓 塅圓 怉慒榓扠怟!怮坵r)c竽t|trt|dkr騮|dttfr6t|dtrt|dtst jd|t|dtr|jr|d|jvr|dS|ddvrt jd|d|ddkr||}|St|tr||ddfSt|tst|tr磘|tr6 t |}n%#t$rt jd |wxYw|jr ||jvr|Sd}t||kr|dz}|dz}t||k|t|d|fSt|trt|St jd |) NrrrrzLame Real value syntax: )rrz Prohibited base for Real value: rzBad real value syntax: ) r6rrrkrqrr_inf_Real__normalizeBase10rrr)r%r&rs r(rz Real.prettyInYs 恊漊 # #" ‥ 癮榰燪渪#璾66 Q"58璖11 Q"58璖11 Q''(OPPP58++ 擨 "'(╠琲"7"7楺攛怮寈榳&&''寉 C楿燿// %慾攋燛))楻慘怑慒怉%慾攋燛))--璼5﹝瑉2竡.ABBB 漷 $ $ << +05 2   s F"F;rc骿 |t|S#t$rYdSwxYw)Nz )rrq OverflowError)r%rYs r(r[zReal.prettyPrintsA >>%++.. .   << 鴖 !$ 22c"|j|jkS)z蠭ndicate PLUS-INFINITY object value Returns ------- : :class:`bool` :obj:`True` if calling object represents plus infinity or :obj:`False` otherwise. )r._plusInfrls r( isPlusInfzReal.isPlusInfs寋榙渕++r)c"|j|jkS)z袸ndicate MINUS-INFINITY object value Returns ------- : :class:`bool` :obj:`True` if calling object represents minus infinity or :obj:`False` otherwise. )r. _minusInfrls r( isMinusInfzReal.isMinusInfs寋榙渘,,r)c|j|jvSr+)r.rrls r(isInfz Real.isInfs寋榙渋''r)c驦|t||zSr+r-rqr/s r(rCz Real.__add__弞妟%++-...r)c ||zSr+rr/s r(rEz Real.__radd__rr)c驦|t||zSr+rr/s r(rKz Real.__mul__rr)c ||zSr+rr/s r(rMz Real.__rmul__rr)c驦|t||z Sr+rr/s r(rGz Real.__sub__rr)c驦||t|z Sr+rr/s r(rIz Real.__rsub__弞妟%%++-...r)c驦|t||zSr+rr/s r(rOz Real.__mod__rr)c驦||t|zSr+rr/s r(rQz Real.__rmod__rr)c骴|tt|||Sr+r-rTrqrUs r(rWz Real.__pow__s&弞妟#漞燚檏渒5&99:::r)c骲|t|t|Sr+rr/s r(rYz Real.__rpow__s$弞妟#榚411222r)c驦|t||z Sr+rr/s r(r`zReal.__truediv__rr)c驦||t|z Sr+rr/s r(rbzReal.__rtruediv__rr)c驦|t||zSr+rr/s r(rfzReal.__divmod__s弞妟%++.///r)c驦||t|zSr+rr/s r(rhzReal.__rdivmod__s弞妟%5;;.///r)c:tt|Sr+)rkrqrls r(rmz Real.__int__s5;;r)c螽|j|jvr|jSt|jdt|jd|jdzS)Nrrr)r.rrqrTrls r(rrzReal.__float__sO ;$) # #;  楢燭癟碵碸!D!DD r)c骮|tt|Sr+)r-rurqrls r(rvz Real.__abs__s"弞妟#漞燚檏渒**+++r)c驢|t| Sr+rrls r(rzz Real.__pos__弞妟5;;,'''r)c驢|t| Sr+rrls r(r}z Real.__neg__rr)c髇tt||}|r||S|Sr+)rrqr-rs r(rzReal.__round__s4 %++榪 ! !  ::榓== 圚r)c骿|tjt|Sr+)r-rrrqrls r(rzReal.__floor__$弞妟$*411222r)c骿|tjt|Sr+)r-rrrqrls r(rz Real.__ceil__s$弞妟$)$00111r)c骿|tjt|Sr+)r-rrrqrls r(rzReal.__trunc__rr)c(t||kSr+rqr/s r(rz Real.__lt__怲墈寋楿""r)c(t||kSr+rr/s r(rz Real.__le__怲墈寋榚##r)c(t||kSr+rr/s r(rz Real.__eq__rr)c(t||kSr+rr/s r(rz Real.__ne__rr)c(t||kSr+rr/s r(rz Real.__gt__rr)c(t||kSr+rr/s r(rz Real.__ge__rr)c:tt|Sr+)boolrqrls r(__bool__z Real.__bool__s旹$慘擪   r)c骮|j|jvrtjd|j|S)Nz Invalid infinite value operation)r.rrrr%idxs r(rzReal.__getitem__ s0 ;$) # ##$FGG G;榮# #r)c|jSr+)rrls r(isPlusInfinityzReal.isPlusInfinity 寏r)c|jSr+)rrls r(isMinusInfinityzReal.isMinusInfinitys r)c|jSr+)rrls r( isInfinityzReal.isInfinitys 寊r)rr+)Brrrr binEncBaserqrrrrr rrrrrrrrrr"rrrwrrr[propertyrrrrCrErKrMrGrIrOrQrWrYr`rbrfrhrmrrrvrzr}rrrrrrrrrrrrrrrrrr)r(rr sx))餞J5<<怑&慚擬 " ##9圫宆%爏':窪AAF5*466K * * , ,F刓& & & 餚     , ,刋 , - -刋 -((刋(//////////////////;;;;333//////000000   ,,,((((((333222333###$$$$$$$$$###$$$!!!"+H$$$s % 33rc笫eZdZdZejejejejdZ e j Z e ZejZdS)raCreate |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.SimpleAsn1Type`, its objects are immutable and duck-type Python :class:`int` objects. Keyword Args ------------ value: :class:`int`, :class:`str` or |ASN.1| object Python :class:`int` or :class:`str` literal or |ASN.1| object. If `value` is not given, schema object will be created. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s). Constraints verification for |ASN.1| type occurs automatically on object instantiation. namedValues: :py:class:`~pyasn1.type.namedval.NamedValues` Object representing non-default symbolic aliases for numbers Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer. Examples -------- .. code-block:: python class RadioButton(Enumerated): ''' ASN.1 specification: RadioButton ::= ENUMERATED { button1(0), button2(1), button3(2) } selected-by-default RadioButton ::= button1 ''' namedValues = NamedValues( ('button1', 0), ('button2', 1), ('button3', 2) ) selected_by_default = RadioButton('button1') rN)rrrrr rrrrrrrrr rrr rr!rr)r(rrs~//餱圫宆%爏':窪AAF5*466K   F'(&((KKKr)rc箢eZdZdZdZdZdZdZdZdZ dd Z d Z dd Z dZ dZdZedfdZedddfdZedZedZdZdZddZddZedZedZd S)ra<Create |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.ConstructedAsn1Type`, its objects are mutable and duck-type Python :class:`list` objects. Keyword Args ------------ componentType : :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A pyasn1 object representing ASN.1 type allowed within |ASN.1| type tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s). Constraints verification for |ASN.1| type can only occur on explicit `.isInconsistent` call. Examples -------- .. code-block:: python class LotteryDraw(SequenceOf): # SetOf is similar ''' ASN.1 specification: LotteryDraw ::= SEQUENCE OF INTEGER ''' componentType = Integer() lotteryDraw = LotteryDraw() lotteryDraw.extend([123, 456, 789]) c蠖|r3td|D]"\}}||vrtjd||d<#t|_t jj|fi|dS)N) componentTyperrz*Conflicting positional and keyword params!r)ziprrr_componentValuesrConstructedAsn1Typer#)r%argsr'keyr&s r(r#zSequenceOfAndSetOfBase.__init__s  0!#23799 0 0 怳&==+,XYYY*/'' '  )$99&99999r)c髗 ||S#tj$r}t|d}~wwxYwr+)getComponentByPositionrrrr%rrs r(rz"SequenceOfAndSetOfBase.__getitem__sI "..╯33 3  " " "楽// ! "鴖:5:c髝 |||dS#tj$r}t|d}~wwxYwr+)setComponentByPositionrrrr%rr&rs r( __setitem__z"SequenceOfAndSetOfBase.__setitem__sQ "  ' '║ 3 3 3 3 3  " " "楽// ! "鴖=8=c骦|jturd}nt|j}|||<dSr)r rr)r%r&poss r(r^zSequenceOfAndSetOfBase.appends6   + +圕圕恉+,,圕圫 r)c髏t|j|Sr+)r:r valuesrr/s r(rzSequenceOfAndSetOfBase.counts-怐)00223399%@@@r)c骽|D]}|||jtur i|_dSdSr+)r^r r)r%rr&s r(extendzSequenceOfAndSetOfBase.extendsJ  圗 廗奒       + +$&圖 ! ! ! , +r)rNc|t|}t|j\}}t |} |||||S#t j$r}t|d}~wwxYwr+) rrr itemsr:rrrr)r%r&startstoprrrs r(rzSequenceOfAndSetOfBase.indexs <恡𕹋圖榯4::<<=恌 "6<<╱癲;;< <  " " "楽// ! "鴖A""B1BBc8|jdSr+)r reverserls r(rzSequenceOfAndSetOfBase.reverses %%'''''r)Fc 髺ttt|j|||_dS)N)r r)dict enumeratesortedr r)r%r rs r(sortzSequenceOfAndSetOfBase.sortsN $ 昮楾299;;!$╣777 8 8!9!9r)c骬|jtus|jsdSt|jdzS)Nrr)r rrrls r(rzSequenceOfAndSetOfBase.__len__s3   + +񳷱H +14())ˋ--r)c#髕Ktdt|D]}||VdSr)rrrrs r(rzSequenceOfAndSetOfBase.__iter__sL滳橧淚&& 3 3圕--╟22 2 2 2 2 3 3r)c0|jD]{\}}|turmt|tjr+||||孲|||寍dSNcloneValueFlag)r rrr6rr rr-r%myCloner*rcomponentValues r(_cloneComponentValuesz,SequenceOfAndSetOfBase._cloneComponentValuess#'#8#>#>#@#@ P P 圕,,榥璬.FGGP22榐111PP2238L8L8N8NOOO P Pr)Tc筲t|tr?ttt }fd||DS|dkr,t |z}|dkrt jd j|}nD#tt jf$r+scYS |j|}YnwxYwtus|j r|SS)a2Return |ASN.1| type component value by position. Equivalent to Python sequence subscription operation (e.g. `[]`). Parameters ---------- idx : :class:`int` Component index (zero-based). Must either refer to an existing component or to N+1 component (if *componentType* is set). In the latter case a new component type gets instantiated and appended to the |ASN.1| sequence. Keyword Args ------------ default: :class:`object` If set and requested component is a schema object, return the `default` object instead of the requested component. instantiate: :class:`bool` If :obj:`True` (default), inner component will be automatically instantiated. If :obj:`False` either existing component or the :class:`NoValue` object will be returned. Returns ------- : :py:class:`~pyasn1.type.base.PyAsn1Item` Instantiate |ASN.1| component type or return existing component value Examples -------- .. code-block:: python # can also be SetOf class MySequenceOf(SequenceOf): componentType = OctetString() s = MySequenceOf() # returns component #0 with `.isValue` property False s.getComponentByPosition(0) # returns None s.getComponentByPosition(0, default=None) s.clear() # returns noValue s.getComponentByPosition(0, instantiate=False) # sets component #0 to OctetString() ASN.1 schema # object and returns it s.getComponentByPosition(0, instantiate=True) # sets component #0 to ASN.1 value object s.setComponentByPosition(0, 'ABCD') # returns OctetString('ABCD') value object s.getComponentByPosition(0, instantiate=False) s.clear() # returns noValue s.getComponentByPosition(0, instantiate=False) c>g|]}|Sr)r)rsubidxdefault instantiater%s r(rzASequenceOfAndSetOfBase.getComponentByPosition..%s;鴢000//MM000r)r&SequenceOf/SetOf index is out of range) r6rrrrrrr rrrisValue)r%rr2r3rr-s` `` r(rz-SequenceOfAndSetOfBase.getComponentByPositions6鴢鮀 恈5 ! ! 0滶#燿)),,--圙000000")#,000 0 77恉))榗/圕怮妛坵'<>>> 8!237圢圢%+, 8 8 8   ' ' , , ,!237圢圢圢  8 昰  !7 ! !圢s BC5"CCc髍t|trnttt |}|r||dpd}t |D]!\}} |||z| |||"|S|dkr,t ||z}|dkrtjd|j } |j turi} n|j } | |t} |tur6| | }n| turtjdn黷|tjs噟 1t| tjr| |}n瘄 tur1t| tjr| |}nutjd|d|| 乊|s|rU|jr| jp| j} | ||o||o|s/| jt*jkrtjd|d | || |<| |_ |S) aAssign |ASN.1| type component by position. Equivalent to Python sequence item assignment operation (e.g. `[]`) or list.append() (when idx == len(self)). Parameters ---------- idx: :class:`int` Component index (zero-based). Must either refer to existing component or to N+1 component. In the latter case a new component type gets instantiated (if *componentType* is set, or given ASN.1 object is taken otherwise) and appended to the |ASN.1| sequence. Keyword Args ------------ value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentType* is set) or ASN.1 value object to assign to |ASN.1| component. If `value` is not given, schema object will be set as a component. verifyConstraints: :class:`bool` If :obj:`False`, skip constraints validation matchTags: :class:`bool` If :obj:`False`, skip component tags matching matchConstraints: :class:`bool` If :obj:`False`, skip component constraints matching Returns ------- self Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer IndexError When idx > len(self) rr4NComponent type not definedr&zNon-ASN.1 value z! and undefined component type at %Component value is tag-incompatible:  vs )r6rrrrr"rrrrr rgetr-rAsn1Itemr"strictConstraintsisSameTypeWith isSuperTypeOfrr)r%rr&verifyConstraints matchTagsmatchConstraintsrstartIdxsubIdxsubValuercomponentValues currentValuesubtypeCheckers r(rz-SequenceOfAndSetOfBase.setComponentByPosition>s鮔 恈5 ! ! 滶#燿)),,--圙2񃝽<?7癮圚$-╡$4$4 1 1 ++榲%爔1B/1111圞 77恉))榗/圕怮妛坵'<>>>*   + + 圤圤#3圤&**388 旼  (%++--(('(DEEE)楨4=11 7)榼璬.ABB*%++%+88--榺璗-@AA.$***77''%*燯燯――2333 &↖ &9I &*1!00!/  ">%):)H竬"3"H8HJJ 7!'3:55++ %爙爙6777 % / r)c,|j |jjSdSr+)rtagMaprls r(componentTagMapz&SequenceOfAndSetOfBase.componentTagMaps   )%, , * )r)c驞fdtjDS)Nc*g|]}j|Srr rrr%s r(rz5SequenceOfAndSetOfBase.components..s1鴢:::%燾*:::r))r#r rls`r( componentsz!SequenceOfAndSetOfBase.componentss9鴢::::!$"788::: :r)ci|_|S)zemove all components and become an empty |ASN.1| value object. Has the same effect on |ASN.1| object as it does on :class:`list` built-in. rNrls r(clearzSequenceOfAndSetOfBase.clears !# r)ct|_|Sz篟emove all components and become a |ASN.1| schema object. See :meth:`isValue` property for more information on the distinction between value and schema objects. )rr rls r(resetzSequenceOfAndSetOfBase.resets !( r)c笾|dz }|jjdz}|js|St|D];\}}|d|zz }|tur |j|dz }#|||z }<|S)Nr:  z)rrr5r"rrr[r%rYrepresentationrr-s r(r[z"SequenceOfAndSetOfBase.prettyPrints  058寍 "! !#,═?? D D 圕 榗燛檏 )圢'))&2)+."<"<窾"C"CCr)c蟠|dz }|jd|jjd}|j%|d|zz }||j|z }|dzd|dz zzdzS)Nr ->  { rX })rrrrprettyPrintType)r%rYrZs r(r`z&SequenceOfAndSetOfBase.prettyPrintTypesv  +/;;;8O8O8OP   ) 榗燛檏 )圢 榙0@@GG G圢$爏╡癮﹊'883>>r)c笠|jturdSt|jt|krdS|jD]}|tus|jsdSdS)arIndicate that |ASN.1| object represents ASN.1 value. If *isValue* is :obj:`False` then this object represents just ASN.1 schema. If *isValue* is :obj:`True` then, in addition to its ASN.1 schema features, this object can also be used like a Python built-in object (e.g. :class:`int`, :class:`str`, :class:`dict` etc.). Returns ------- : :class:`bool` :obj:`False` if object represents just ASN.1 schema. :obj:`True` if object represents ASN.1 schema and can be used as a normal value. Note ---- There is an important distinction between PyASN1 schema and value objects. The PyASN1 schema objects can only participate in ASN.1 schema-related operations (e.g. defining or testing the structure of the data). Most obvious uses of ASN.1 schema is to guide serialisation codecs whilst encoding/decoding serialised ASN.1 contents. The PyASN1 value objects can **additionally** participate in many operations involving regular Python objects (e.g. arithmetic, comprehension etc). FT)r rrrr5r%r-s r(r5zSequenceOfAndSetOfBase.isValues|6   + +5 坱$ % %═ 2 25"3::<<  圢((0F(恥恥)坱r)c|jtus|jsdS|jturdSi}|jD]\}}|tur|||< ||n#t j$r }|cYd}~Sd}~wwxYwdSaRun necessary checks to ensure |ASN.1| object consistency. Default action is to verify |ASN.1| object against constraints imposed by `subtypeSpec`. Raises ------ :py:class:`~pyasn1.error.PyAsn1tError` on any inconsistencies found FTN)rrrr rrr)r%mappingrr&rs r(isInconsistentz%SequenceOfAndSetOfBase.isInconsistent s   ( (0@ (5   + +4/5577 ! !塉圕 圙怌塋圠    榃 % % % %    圝圝圝圝圝圝 坲sA//B >B?B B )rNNFr)rrrrr#rrr^rrrrr$rrr.rrrrrKrPrRrUr[r`r5rfrr)r(rrcs!!餌 : : :""""""AAA''' " " " "(((9999 ... 333PPP3:纓[[[[饅1815)-04mmmm館--刋-::刋:"????$$刋$餖  刋   r)rc蠛eZdZejZejejejej dZ dZ e j ZeZdS)rrNrrrrrr rrrtagFormatConstructedrrrrrrrrr)r(rr-髉$,G 圫宆%爏'?FFF M 5*466K$ - - / /FFFr)rc蠛eZdZejZejejejej dZ dZ e j ZeZdS)rNrirr)r(rrDrkr)rc6eZdZdZejZGddeZdZ dZ dZ dZ dZ d Zd Zd Zd Zd ZdZdZedZdZedfdZedddfdZedfdZedddfdZedZedZd dZd dZ dZ!dZ"dZ#dS)!raCreate |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.ConstructedAsn1Type`, its objects are mutable and duck-type Python :class:`dict` objects. Keyword Args ------------ componentType: :py:class:`~pyasn1.type.namedtype.NamedType` Object holding named ASN.1 types allowed within this collection tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s). Constraints verification for |ASN.1| type can only occur on explicit `.isInconsistent` call. Examples -------- .. code-block:: python class Description(Sequence): # Set is similar ''' ASN.1 specification: Description ::= SEQUENCE { surname IA5String, first-name IA5String OPTIONAL, age INTEGER DEFAULT 40 } ''' componentType = NamedTypes( NamedType('surname', IA5String()), OptionalNamedType('first-name', IA5String()), DefaultedNamedType('age', Integer(40)) ) descr = Description() descr['surname'] = 'Smith' descr['first-name'] = 'John' c驜eZdZdZdZdZdZdZdZdZ dZ d Z d S) SequenceAndSetBase.DynamicNamesz9Fields names/positions mapping for component-less objectsc"i|_i|_dSr+ _keyToIdxMap _idxToKeyMaprls r(r#z(SequenceAndSetBase.DynamicNames.__init__s "圖  "圖   r)c*t|jSr+)rrsrls r(rz'SequenceAndSetBase.DynamicNames.__len__s恡()) )r)c&||jvp||jvSr+rrr%items r(rnz,SequenceAndSetBase.DynamicNames.__contains__s4,,I8I0I Ir)c骬fdttjDS)Nc32K|]}j|VdSr+)rtrOs r(rXz;SequenceAndSetBase.DynamicNames.__iter__..s+TT╯怐%燾*TTTTTTr))rrrtrls`r(rz(SequenceAndSetBase.DynamicNames.__iter__s0鴢TTTT礶紺訞QdSr+)rrrrrr/rs r(rzSequenceAndSetBase.itemss/J3皌7I3J3JKK 9 9圕% 9(-2癉碔=====(-╰癈瑈88888  9 9r)c驚|D] \}}|||< |D] }||||<dSr+r)r% iterValue mappingValuekras r(updatezSequenceAndSetBase.updatesH  塂圓坬圖塆圙 & &圓"1攐圖塆圙 & &r)c驠g|_||_|S)zemove all components and become an empty |ASN.1| value object. Has the same effect on |ASN.1| object as it does on :class:`dict` built-in. )r rrrls r(rRzSequenceAndSetBase.clear s% !#!..00 r)c驪t|_||_|SrT)rr rrrls r(rUzSequenceAndSetBase.reset s% !(!..00 r)c|jSr+rNrls r(rPzSequenceAndSetBase.components s $$r)c驠|jturdSt|jD]{\}}|turmt|tjr+||||孲|||寍dSr()r rr"r6rr rr-r+s r(r.z(SequenceAndSetBase._cloneComponentValues s   + + 團#,═-B#C#C P P 圕,,榥璬.FGGP22榐111PP2238L8L8N8NOOO P Pr)Tc篾|jr|j|}nB |j|}n&#t$rt jd|dwxYw||||S)apReturns |ASN.1| type component by name. Equivalent to Python :class:`dict` subscription operation (e.g. `[]`). Parameters ---------- name: :class:`str` |ASN.1| type component name Keyword Args ------------ default: :class:`object` If set and requested component is a schema object, return the `default` object instead of the requested component. instantiate: :class:`bool` If :obj:`True` (default), inner component will be automatically instantiated. If :obj:`False` either existing component or the :class:`NoValue` object will be returned. Returns ------- : :py:class:`~pyasn1.type.base.PyAsn1Item` Instantiate |ASN.1| component type or return existing component value rrr2r3)rrrrrrrr)r%r/r2r3rs r(rz%SequenceAndSetBase.getComponentByName' s8  ! G$66皌<<圕圕 G(::4@@ G G G''竧竧竧(EFFF G**3萚*YYY ?#A"c簏|jr|j|}nB |j|}n&#t$rt jd|dwxYw||||||S)aAssign |ASN.1| type component by name. Equivalent to Python :class:`dict` item assignment operation (e.g. `[]`). Parameters ---------- name: :class:`str` |ASN.1| type component name Keyword Args ------------ value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentType* is set) or ASN.1 value object to assign to |ASN.1| component. If `value` is not given, schema object will be set as a component. verifyConstraints: :class:`bool` If :obj:`False`, skip constraints validation matchTags: :class:`bool` If :obj:`False`, skip component tags matching matchConstraints: :class:`bool` If :obj:`False`, skip component constraints matching Returns ------- self rr)rrrrrrrr)r%r/r&r@rArBrs r(rz%SequenceAndSetBase.setComponentByNameN s養  ! G$66皌<<圕圕 G(::4@@ G G G''竧竧竧(EFFF G** )񜲨F   rc$ |jturt}n |j|}n#t$r t}YnwxYw|s|tus|js|S|S|tur|||j|}|tus|jr|S|S)aReturns |ASN.1| type component by index. Equivalent to Python sequence subscription operation (e.g. `[]`). Parameters ---------- idx: :class:`int` Component index (zero-based). Must either refer to an existing component or (if *componentType* is set) new ASN.1 schema object gets instantiated. Keyword Args ------------ default: :class:`object` If set and requested component is a schema object, return the `default` object instead of the requested component. instantiate: :class:`bool` If :obj:`True` (default), inner component will be automatically instantiated. If :obj:`False` either existing component or the :class:`NoValue` object will be returned. Returns ------- : :py:class:`~pyasn1.type.base.PyAsn1Item` a PyASN1 object Examples -------- .. code-block:: python # can also be Set class MySequence(Sequence): componentType = NamedTypes( NamedType('id', OctetString()) ) s = MySequence() # returns component #0 with `.isValue` property False s.getComponentByPosition(0) # returns None s.getComponentByPosition(0, default=None) s.clear() # returns noValue s.getComponentByPosition(0, instantiate=False) # sets component #0 to OctetString() ASN.1 schema # object and returns it s.getComponentByPosition(0, instantiate=True) # sets component #0 to ASN.1 value object s.setComponentByPosition(0, 'ABCD') # returns OctetString('ABCD') value object s.getComponentByPosition(0, instantiate=False) s.clear() # returns noValue s.getComponentByPosition(0, instantiate=False) )r rrr5r)r%rr2r3r-s r(rz)SequenceAndSetBase.getComponentByPosition| s餒 %$//!("&!6皊!; % % %$圢圢圢 % &((0F(%% 漌 $ $  ' ' , , ,.╯3 昰  !7 ! !圢s #&::c骦|j}|j}|jturg}n|j} ||} n>#t$r1t} |r%||krt jdtg|z}YnwxYw|turs|rR||}t|tj r!| ||j }np| turt jdnQt|tj s膢rg||} t| tjr| |}n飔 jd|jjz| tur1t| tjr| |}n攖 jd|jjz|s|s|rm|rk||} | turM|jr| jp| j} | ||o||o|s'||jst jd|d||s ||jvr|||<nWt-||kr0|||j|nt jd ||_|S) aAssign |ASN.1| type component by position. Equivalent to Python sequence item assignment operation (e.g. `[]`). Parameters ---------- idx : :class:`int` Component index (zero-based). Must either refer to existing component (if *componentType* is set) or to N+1 component otherwise. In the latter case a new component of given ASN.1 type gets instantiated and appended to |ASN.1| sequence. Keyword Args ------------ value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentType* is set) or ASN.1 value object to assign to |ASN.1| component. If `value` is not given, schema object will be set as a component. verifyConstraints : :class:`bool` If :obj:`False`, skip constraints validation matchTags: :class:`bool` If :obj:`False`, skip component tags matching matchConstraints: :class:`bool` If :obj:`False`, skip component constraints matching Returns ------- self zcomponent index out of ranger)r7r8z%s can cast only scalar valuesz%s undefined component typer9r:zComponent index out of range)rrr rrrrgetTypeByPositionr6rr r- isDefaultedr<r"rrr=r>r?openTyperrr^r) r%rr&r@rArBrcomponentTypeLenrFrGsubComponentTyperHs r(rz)SequenceAndSetBase.setComponentByPosition s8餒* 1   + + 圤圤#3圤 ?*3/圠圠 ? ? ?"圠 ?#燾))+,JKKK#*).>">  ? 旼   F%77<<榚%=>>W!烱欿皚繱7I7U楰VV怑(('(DEEE)楨4=11 z j#0#B#B3#G#G .0CDDq,222??怑怑 +,L葈設f設o,oppp,,窵$訨]1^1^,$***77'(E 訦_訦h(hiii z營 z1A z z,>>竤CC .."&"8#B"2"A#A"2"@&悀爀->-L9&7&L\}}|js|jr|jsdS|j|}|tus|jsdS?n|jD]}|tus|jsdSdS)aIndicate that |ASN.1| object represents ASN.1 value. If *isValue* is :obj:`False` then this object represents just ASN.1 schema. If *isValue* is :obj:`True` then, in addition to its ASN.1 schema features, this object can also be used like a Python built-in object (e.g. :class:`int`, :class:`str`, :class:`dict` etc.). Returns ------- : :class:`bool` :obj:`False` if object represents just ASN.1 schema. :obj:`True` if object represents ASN.1 schema and can be used as a normal value. Note ---- There is an important distinction between PyASN1 schema and value objects. The PyASN1 schema objects can only participate in ASN.1 schema-related operations (e.g. defining or testing the structure of the data). Most obvious uses of ASN.1 schema is to guide serialisation codecs whilst encoding/decoding serialised ASN.1 contents. The PyASN1 value objects can **additionally** participate in many operations involving regular Python objects (e.g. arithmetic, comprehension etc). It is sufficient for |ASN.1| objects to have all non-optional and non-defaulted components being value objects to be considered as a value objects as a whole. In other words, even having one or more optional components not turned into value objects, |ASN.1| object is still considered as a value object. Defaulted components are normally value objects by default. FT)r rrr" namedTypesr isOptionalr5)r%rrrr-s r(r5zSequenceAndSetBase.isValueE s餌   + +5*  !)2=3K)L)L ! !%%#/3C3N,! 𪍇!%!6皊!;!,,癗4J, 𪍇- !#'"7 ! !!,,癗4J, 𪍇-坱r)c驢|jtus|jsdS|jturdSi}t |jD].\}}|tur|j|}|||</ ||n#t j$r }|cYd}~Sd}~wwxYwdSrd)rrrr r"r}rr)r%rerr&r/rs r(rfz!SequenceAndSetBase.isInconsistent s   ( (0@ (5   + +4#燚$9:: " "塉圕%77<<圖!圙怐塎圡    榃 % % % %    圝圝圝圝圝圝 坲s.BBBBBrc驦|dz }|jjdz}t|jD]z\}}|turl|jre|d|zz }|jr||j|z }n||j|z }|d| |d}寋|S)z歊eturn an object representation string. Returns ------- : :class:`str` Human-friendly object representation. rrWrX=r^) rrr"r rr5rr}rr[rYs r(r[zSequenceAndSetBase.prettyPrint s  058#,═-B#C#C   圕,,1G,#+-%P"燿&8&J&J3&O&OO怤怤"燿&8&J&J3&O&OO怤"怤怤燦$>$>竨$E$E$E$E"r)c髽|dz }|jd|jjd}t|jp|jD]p\}}|d|zz }|jr!|d|j|zz }n |d|j|zz }|d| |d}宷|dzd|dz zzdzS) Nrr\r]rXz"%s"z = r^r_) rrrr"rrr r}rr`)r%rYrZrrs r(r`z"SequenceAndSetBase.prettyPrintType s  +/;;;8O8O8OP"+―,>,E,E,G,G,`4訩`"a"a   圕 榗燛檏 )圢! U&4+=+O+O蠵S+T+T"TT&4+=+O+O蠵S+T+T"TT = =竐 D D D D圢圢$爏╡癮﹊'883>>r)c|Sr+rrls r(setDefaultComponentsz'SequenceAndSetBase.setDefaultComponents  r)c"|jr|jSdSr+)rrrls r(getComponentTypez#SequenceAndSetBase.getComponentType s  ! &% % & &r)c8|jr|j|jSdSr+)rrr/rs r(r}z$SequenceAndSetBase.getNameByPosition s(  ! 0%燾*/ / 0 0r)Nr)$rrrrr NamedTypesrobjectrr#rrrnrrrrrrrRrUrrPr.rrrrrr5rfr[r`rrr}rr)r(rr[sW**餤)怚(**M&6&6&6&6&6恦&6&6&6餜KKK&&&"&&&"--- ***>>> 999&&& %%刋% P P P07繢%Z%Z%Z%Z餘.5-1%),0, , , , 餦3:纓\\\\饇1815)-04iiii餠77刋7餽""刋"餒, ? ? ? ? &&&00000r)rc筻eZdZejZejejejej dZ e j Z ejZeZdZdZdS)rrc驢|jr|j|SdSr+)rgetTagMapNearPositionrs r(getComponentTagMapNearPositionz'Sequence.getComponentTagMapNearPosition s1   A%;;窩@@ @ A Ar)c驤|jr|j||S|Sr+)rgetPositionNearType)r%rrs r(getComponentPositionNearTypez%Sequence.getComponentPositionNearType s+   %99&#FF F圝r)N)rrrrrr rrrrjrrrrrrrrrrrrr)r(rr s (G 圫宆%爏'?FFF5*466K)怚(**M ) ) + +FAAAr)rceZdZejZejejejej dZ e j Z ejZeZd dZeddfdZeddddfdZedZdS) rrmFc|Sr+r)r% innerFlags r( getComponentzSet.getComponent rr)Tc罄||j|||}|r+t|tr|dS|S)a8Returns |ASN.1| type component by ASN.1 tag. Parameters ---------- tagSet : :py:class:`~pyasn1.type.tag.TagSet` Object representing ASN.1 tags to identify one of |ASN.1| object component Keyword Args ------------ default: :class:`object` If set and requested component is a schema object, return the `default` object instead of the requested component. instantiate: :class:`bool` If :obj:`True` (default), inner component will be automatically instantiated. If :obj:`False` either existing component or the :class:`noValue` object will be returned. Returns ------- : :py:class:`~pyasn1.type.base.PyAsn1Item` a pyasn1 object rTr)rrgetPositionByTyper6rr)r%rr2r3rr-s r(getComponentByTypezSet.getComponentByType sq644   0 0 8 85    "燦礐88 "!...>> >" !r)c驚|j|}|rj|j|}|jr||||||S||}|||||||S||||||S)a!Assign |ASN.1| type component by ASN.1 tag. Parameters ---------- tagSet : :py:class:`~pyasn1.type.tag.TagSet` Object representing ASN.1 tags to identify one of |ASN.1| object component Keyword Args ------------ value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentType* is set) or ASN.1 value object to assign to |ASN.1| component. If `value` is not given, schema object will be set as a component. verifyConstraints : :class:`bool` If :obj:`False`, skip constraints validation matchTags: :class:`bool` If :obj:`False`, skip component tags matching matchConstraints: :class:`bool` If :obj:`False`, skip component constraints matching innerFlag: :class:`bool` If :obj:`True`, search for matching *tagSet* recursively. Returns ------- self r)rrrrrrsetComponentByType) r%rr&r@rArBrrrs r(rzSet.setComponentByType7 s餒 226::   .@@EE圡# 22 19>N!% ; ;窩 @ @ $77楨#4癷蠥Q衇f8..怳-▂:J r)c,|jr |jjSdSr+)r tagMapUniquerls r(rKzSet.componentTagMapn s#   3%2 2 3 3r)NF)rrrrrr rrrrjrrrrrrrrrrrrrrrKrr)r(rr s (G 圫宆%爏'?FFF )怚(**M 5*466K ) ) + +F29'+皍$"$"$"$"餖07-1%),0%* 5555餹33刋333r)rc髮eZdZdZejZejZ e j e j ddZ eZdZdZdZdZdZdZd Zd Zd Zd Zd ZdZdZdZdZdZ e!dfdZ"e!dddfdZ#e$dZ%e$dZ&ddZ'ddZ(e$dZ)dZ*dZ+dS)raCreate |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.ConstructedAsn1Type`, its objects are mutable and duck-type Python :class:`list` objects. Keyword Args ------------ componentType: :py:class:`~pyasn1.type.namedtype.NamedType` Object holding named ASN.1 types allowed within this collection tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s). Constraints verification for |ASN.1| type can only occur on explicit `.isInconsistent` call. Examples -------- .. code-block:: python class Afters(Choice): ''' ASN.1 specification: Afters ::= CHOICE { cheese [0] IA5String, dessert [1] IA5String } ''' componentType = NamedTypes( NamedType('cheese', IA5String().subtype( implicitTag=Tag(tagClassContext, tagFormatSimple, 0) ), NamedType('dessert', IA5String().subtype( implicitTag=Tag(tagClassContext, tagFormatSimple, 1) ) ) afters = Afters() afters['cheese'] = 'Mascarpone' rNc驤|jr|j|j|kStSr+r  _currentIdxNotImplementedrs r(rz Choice.__eq__ *   D()9:竐C Cr)c驤|jr|j|j|kStSr+rrs r(rz Choice.__ne__ rr)c驤|jr|j|j|kStSr+rrs r(rz Choice.__lt__ *   C()9:窾B Br)c驤|jr|j|j|kStSr+rrs r(rz Choice.__le__ rr)c驤|jr|j|j|kStSr+rrs r(rz Choice.__gt__ rr)c驤|jr|j|j|kStSr+rrs r(rz Choice.__ge__ rr)c*t|jSr+)rr rls r(rzChoice.__bool__ s怐)***r)c|jdurdpdS)Nrr)rrls r(rzChoice.__len__ s爐+16癚6r)c骴|jdS||j|jkSrgrrgetNamers r(rnzChoice.__contains__ s2   #5恉()9:BBDDDDr)c#髍K|jt|j|jVdSr+)r StopIterationrrrls r(rzChoice.__iter__ s>   #  !12::<<<<<<>@@ @ @ @ @ @ ( 'r)c#髠K|j5|j|j||jfVdSdSr+rrls r(rz Choice.items sM   '$燭%56>>@@$纓訥W訠XX X X X X X ( 'r)c<|jtjddS)NComponent not chosen)rrrrls r(checkConsistencyzChoice.checkConsistency s%   ##$:;; ; $ #r)c髝 |}t|tr|j}n|j}t|t jr,||||dS|||dS#tj $rYdSwxYwr() rr6reffectiveTagSetrrr rr-rr)r%r,r* componentrs r(r.zChoice._cloneComponentValues s F))++圛),, *"2"))%=>> F**業烵歄>極JJ**񛲧??3D3DEEEEE     圖圖 鴖B**B=<B=Tc髷tj}|j |j|krt||||S|j|S)Nr)rrrrr )r%rr2r3rs r(rzChoice.getComponentByPosition sX+   #爐'73'>'>--╠癈:E.GG G$燬))r)c髱|j}t||||||||_|||krt|j|<|S)a Assign |ASN.1| type component by position. Equivalent to Python sequence item assignment operation (e.g. `[]`). Parameters ---------- idx: :class:`int` Component index (zero-based). Must either refer to existing component or to N+1 component. In the latter case a new component type gets instantiated (if *componentType* is set, or given ASN.1 object is taken otherwise) and appended to the |ASN.1| sequence. Keyword Args ------------ value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentType* is set) or ASN.1 value object to assign to |ASN.1| component. Once a new value is set to *idx* component, previous value is dropped. If `value` is not given, schema object will be set as a component. verifyConstraints : :class:`bool` If :obj:`False`, skip constraints validation matchTags: :class:`bool` If :obj:`False`, skip component tags matching matchConstraints: :class:`bool` If :obj:`False`, skip component constraints matching Returns ------- self )rrrrr )r%rr&r@rArBoldIdxs r(rzChoice.setComponentByPosition sU餔! ""4╡5F 蠸cddd  &–--,3圖 !& ) r)c骉|jr|jS|}|jS)zwReturn a :class:`~pyasn1.type.tag.TagSet` object of the currently initialized component or self (if |ASN.1| is tagged).)rrr)r%rs r(rzChoice.effectiveTagSet< s0 ; -; ))++圛, ,r)c骹|jrtj|S|jjSz"Return a :class:`~pyasn1.type.tagmap.TagMap` object mapping ASN.1 tags to ASN.1 objects contained within callee. )rrrJfgetrrrls r(rJz Choice.tagMapE s. ; 3:??4(( (%2 2r)Fc蟾|jtjd|j|j}|r*t |t r||S|S)z砇eturn currently assigned component of the |ASN.1| object. Returns ------- : :py:class:`~pyasn1.type.base.PyAsn1Item` a PyASN1 object Nr)rrrr r6rrr%rcs r(rzChoice.getComponentO s_   ##$:;; ;%燿&67圓 漐622 梸拁爄000r)c篁|jtjd|r<|j|j}t |t r||S|j|jS)z璕eturn the name of currently assigned component of the |ASN.1| object. Returns ------- : :py:class:`str` |ASN.1| component name Nr) rrrr r6rrrr}rs r(rzChoice.getName` su   ##$:;; ; 0)$*:;榓((0񀾗燳///%778HII Ir)c骕|jdS|j|j}|tuo|jS)a~Indicate that |ASN.1| object represents ASN.1 value. If *isValue* is :obj:`False` then this object represents just ASN.1 schema. If *isValue* is :obj:`True` then, in addition to its ASN.1 schema features, this object can also be used like a Python built-in object (e.g. :class:`int`, :class:`str`, :class:`dict` etc.). Returns ------- : :class:`bool` :obj:`False` if object represents just ASN.1 schema. :obj:`True` if object represents ASN.1 schema and can be used as a normal value. Note ---- There is an important distinction between PyASN1 schema and value objects. The PyASN1 schema objects can only participate in ASN.1 schema-related operations (e.g. defining or testing the structure of the data). Most obvious uses of ASN.1 schema is to guide serialisation codecs whilst encoding/decoding serialised ASN.1 contents. The PyASN1 value objects can **additionally** participate in many operations involving regular Python objects (e.g. arithmetic, comprehension etc). NF)rr rr5rbs r(r5zChoice.isValueq s58   #5.╰/?@,G1GGr)c驞d|_t|Sr+)rrrRrls r(rRz Choice.clear s弝妝r)c|jSr+) minTagSetrls r( getMinTagSetzChoice.getMinTagSet rr)r),rrrrr TagSetrrrrrrValueSizeConstraintrrrrrrrrrrrrrrnrrrrrr.rrrrrrJrrr5rRrrr)r(rrt sF++館圫孼塡孿F)怚(**M 5*4& &爍!,,K 廬奭塤宊FK      +++777EEE ===:::AAAYYY<<<FFF"3:纓****1815)-04****餢--刋-33刋3"JJJJ" H H刋 H餌 r)rc髮eZdZdZejZejZ e Z e dZdS)raCreate |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.SimpleAsn1Type`, its objects are immutable and duck-type :class:`bytes`. When used in Unicode context, |ASN.1| type assumes "|encoding|" serialisation. Keyword Args ------------ value: :class:`unicode`, :class:`str`, :class:`bytes` or |ASN.1| object :class:`bytes`, alternatively :class:`str` representing character string to be serialised into octets (note `encoding` parameter) or |ASN.1| object. If `value` is not given, schema object will be created. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s). Constraints verification for |ASN.1| type occurs automatically on object instantiation. encoding: :py:class:`str` Unicode codec ID to encode/decode :class:`str` the payload when |ASN.1| object is used in text string context. binValue: :py:class:`str` Binary string initializer to use instead of the *value*. Example: '10110011'. hexValue: :py:class:`str` Hexadecimal string initializer to use instead of the *value*. Example: 'DEADBEEF'. Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer. Examples -------- .. code-block:: python class Error(Sequence): ''' ASN.1 specification: Error ::= SEQUENCE { code INTEGER, parameter ANY DEFINED BY code -- Either INTEGER or REAL } ''' componentType=NamedTypes( NamedType('code', Integer()), NamedType('parameter', Any(), openType=OpenType('code', {1: Integer(), 2: Real()})) ) error = Error() error['code'] = 1 error['parameter'] = Integer(1234) c蠛 |jS#t$rGtj|j|it jjt ji||_|jcYSwxYwr)_tagMapAttributeErrorr TagMaprr endOfOctetsrls r(rJz Any.tagMap si <    !=榙#'9圖孡 <    鴖 堿AAN)rrrrr rrrrrrrrrrJrr)r(rr sn@@餒圫孼塡孿F 5*466K " " $ $F   刋   r)r)'rrpyasn1rpyasn1.codec.berr pyasn1.compatr pyasn1.typerrrr r r rr__all__r"r r rkrrrrrrrrr rrrrrrrrrr)r(rsh  !!!!!!""""""!!!!!!  , ')) ! ! !c c c c c 坉!c c c 餖=!=!=!=!=!坓=!=!=!餈     3   ]]]]]#]]]餈 S%S%S%S%S%$%S%S%S%餷11111;111餳H1H1H1H1H1恡*H1H1H1餠~1~1~1~1~1$%~1~1~1養NNNNN4 NNN餬B)B)B)B)B)B)B)B)餘HHHHH楾5HHH餞00000'000.00000 "000.x 0x 0x 0x 0x 01x 0x 0x 0餿     !   餏y3y3y3y3y3 y3y3y3饃ggggg圫ggg餞 ^ ^ ^ ^ ^ +^ ^ ^ ^ ^ r)PK!= 柚鑡鑡 __pycache__/base.cpython-311.pycnu刐迭 辤"V篁ddlZddlmZddlmZddlmZddlmZgdZGddeZ Gd d e Z e Z Gd d eZ e Z Gd de ZeZGdde ZeZdS)N)error) constraint)tag)tagmap)Asn1ItemAsn1TypeSimpleAsn1TypeConstructedAsn1Typec&eZdZeddZdS)rc髝 txj|z c_n#t$r|t_YnwxYwtjSN)r _typeCounterAttributeError)cls increments 鷓/builddir/build/BUILD/imunify360-venv-2.6.2/opt/imunify360/venv/lib/python3.11/site-packages/pyasn1/type/base.py getTypeIdzAsn1Item.getTypeIdsP .  ! !燳 . ! ! ! . . .$-岺 ! ! ! .$$s 11N)r )__name__ __module__ __qualname__ classmethodrrrrs2%%%刐%%%rrc篁eZdZdZejZejZ dZ dZ dZ dZ edZedZedZdd Zdd Zed ZddZdZdZdZdZdZdS)ra>Base class for all classes representing ASN.1 types. In the user code, |ASN.1| class is normally used only for telling ASN.1 objects from others. Note ---- For as long as ASN.1 is concerned, a way to compare ASN.1 types is to use :meth:`isSameTypeWith` and :meth:`isSuperTypeOf` methods. Nc 髳|j|jd}|||j|||_dS)NtagSet subtypeSpec)rrupdate__dict__ _readOnlyselfkwargsreadOnlys r__init__zAsn1Type.__init__2sN攌+    榅&&&!rc髍|ddkr ||jvrtjd|z||j|<dS)Nr_z!read-only instance attribute "%s")r"r PyAsn1Errorr!)r$namevalues r __setattr__zAsn1Type.__setattr__>sD 7恈>>榙燿44#$G$$NOO O# 恉rc*|Sr) prettyPrintr$s r__str__zAsn1Type.__str__Ds!!!rc|jSr)r"r0s rr&zAsn1Type.readOnlyGs 寏rc|jS)z3For |ASN.1| type is equivalent to *tagSet* rr0s reffectiveTagSetzAsn1Type.effectiveTagSetKs 寋rc8tj|j|iS)zvReturn a :class:`~pyasn1.type.tagmap.TagMap` object mapping ASN.1 tags to ASN.1 objects within callee object. )rTagMaprr0s rtagMapzAsn1Type.tagMapQs寎榙渒40111rTc骎||up%| s|j|jko| p|j|jkS)a?Examine |ASN.1| type for equality with other ASN.1 type. ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints (:py:mod:`~pyasn1.type.constraint`) are examined when carrying out ASN.1 types comparison. Python class inheritance relationship is NOT considered. Parameters ---------- other: a pyasn1 type object Class instance representing ASN.1 type. Returns ------- : :class:`bool` :obj:`True` if *other* is |ASN.1| type, :obj:`False` otherwise. rr$other matchTagsmatchConstraintss risSameTypeWithzAsn1Type.isSameTypeWithWsF( P=$+"=P%%N)9窾=N)N Qrc髪| p@|j|jo!| p|j|jS)alExamine |ASN.1| type for subtype relationship with other ASN.1 type. ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints (:py:mod:`~pyasn1.type.constraint`) are examined when carrying out ASN.1 types comparison. Python class inheritance relationship is NOT considered. Parameters ---------- other: a pyasn1 type object Class instance representing ASN.1 type. Returns ------- : :class:`bool` :obj:`True` if *other* is a subtype of |ASN.1| type, :obj:`False` otherwise. )risSuperTagSetOfr isSuperTypeOfr:s rrAzAsn1Type.isSuperTypeOfosO( ],,║琝::]&&[$*:*H*H訧Z*[*[ ^rc(|D]}|turdSdS)NFT)noValue)valuesr,s r isNoValuezAsn1Type.isNoValues-  圗滸##恥恥$坱rrctr)NotImplementedErrorr$scopes rr/zAsn1Type.prettyPrints!!rc|jSrr4r0s r getTagSetzAsn1Type.getTagSet 寋rc|jSr)r5r0s rgetEffectiveTagSetzAsn1Type.getEffectiveTagSets ##rc|jSr)r8r0s r getTagMapzAsn1Type.getTagMaprLrc|jSrrr0s rgetSubtypeSpeczAsn1Type.getSubtypeSpecs rc|jSr)isValuer0s rhasValuezAsn1Type.hasValues 寍r)TTr)rrr__doc__rTagSetrrConstraintsIntersectionrtypeIdr'r-r1propertyr&r5r8r>rA staticmethodrEr/rKrNrPrSrVrrrrrsn  圫孼塡孿F5*466KF " " "$$$ """刋刋 22刋2 QQQQ0^^^^0刓 """" $$$   rrc0eZdZdZhdZdZdZdZdZdS)NoValueazCreate a singleton instance of NoValue class. The *NoValue* sentinel object represents an instance of ASN.1 schema object as opposed to ASN.1 value object. Only ASN.1 schema-related operations can be performed on ASN.1 schema objects. Warning ------- Any operation attempted on the *noValue* object will raise the *PyAsn1Error* exception. >__del____new__r'__repr__im_class __class__ __slots__ __reduce__ __sizeof__ __delattr__ __getattr__r- __getstate__ __objclass__r __setstate__ __reduce_ex____getnewargs____getinitargs____getattribute__Ncjtd}fdttttfD}t |D]}t |||t_jS)Ncfd}|S)Nc2tjdz)N/Attempted "%s" operation on ASN.1 schema objectrr*)r$argskwr+s rplugz.NoValue.__new__..getPlug..plugs鴢+,]衊d,deeerr)r+rxs` rgetPlugz NoValue.__new__..getPlugs&鴢fffff rc 筘g|]f}t|D]T}|jv |d |d5t t ||疪|孶実S)__)dir skipMethods startswithendswithcallablegetattr).0typr+rs r z#NoValue.__new__..s鴢;;;$';;  77 烵歄―118 烳歁$//8%⊿$%7%78888777r) _instancestrintlistdictsetsetattrobjectra)rryop_namesr+s` rrazNoValue.__new__s鴢 =     ;;;;$'璬礑#9;;;圚楬  2 2楾񃜱4==1111"烴歂3//圕孧寎rc骹||jvrtd|ztjd|z)NzAttribute %s not presentrt)r}rrr*)r$attrs rrizNoValue.__getattr__s< 4# # # !;竏!BCC C Q蠺X XYYYrc d|jjzS)Nz <%s object>)rdrr0s rrbzNoValue.__repr__s榯渵666r) rrrrXr}rrarirbrrrr_r_sf  K4I,ZZZ 77777rr_c鬁eZdZdZeZefdZdZdZdZ dZ dZ dZ d Z d Zd Zed Zefd ZefdZdZdZddZddZdS)r aBase class for all simple classes representing ASN.1 types. ASN.1 distinguishes types by their ability to hold other objects. Scalar types are known as *simple* in ASN.1. In the user code, |ASN.1| class is normally used only for telling ASN.1 objects from others. Note ---- For as long as ASN.1 is concerned, a way to compare ASN.1 types is to use :meth:`isSameTypeWith` and :meth:`isSuperTypeOf` methods. c .tj|fi||tur|j}nj||} ||n>#t j$r,}t||d|j j d}~wwxYw||_ dS)Nz at ) rr'rC defaultValueprettyInrrr*typerdr_value)r$r,r%exValues rr'zSimpleAsn1Type.__init__s$))&))) 旼  %圗圗桵扢%((圗 U  ''''$ U U U#昫7憁攎'''4>;R;R$STTT U sAB 'BB c6|jjd|jrdpdd}|jD]\}}|r |d|d|z }|jrG|}t |dkr|dddz|d dz}|d |zz }d |zS) N r,schema object, z...i, payload [%s]<%s>)rdrrUr&itemsr/lenr$representationrr,s rrbzSimpleAsn1Type.__repr__s 孨 # # #燭%=癵%I%I%IK =..00 < <塊圖% <╰╰╰癠癠";; < 7$$&&圗5墇寊楤榗榬榗 燯*║񳞞4琜8 .6 6圢&&rc$||urdS|j|kS)NTrr$r;s r__eq__zSimpleAsn1Type.__eq__#s 5==4寋榚##rc|j|kSrrrs r__ne__zSimpleAsn1Type.__ne__(寋榚##rc|j|kSrrrs r__lt__zSimpleAsn1Type.__lt__+寋楿""rc|j|kSrrrs r__le__zSimpleAsn1Type.__le__.rrc|j|kSrrrs r__gt__zSimpleAsn1Type.__gt__1rrc|j|kSrrrs r__ge__zSimpleAsn1Type.__ge__4rrc*t|jSr)boolrr0s r__bool__zSimpleAsn1Type.__bool__7怐擪   rc*t|jSr)hashrr0s r__hash__zSimpleAsn1Type.__hash__:rrc|jtuS)azIndicate that |ASN.1| object represents ASN.1 value. If *isValue* is :obj:`False` then this object represents just ASN.1 schema. If *isValue* is :obj:`True` then, in addition to its ASN.1 schema features, this object can also be used like a Python built-in object (e.g. :class:`int`, :class:`str`, :class:`dict` etc.). Returns ------- : :class:`bool` :obj:`False` if object represents just ASN.1 schema. :obj:`True` if object represents ASN.1 schema and can be used as a normal value. Note ---- There is an important distinction between PyASN1 schema and value objects. The PyASN1 schema objects can only participate in ASN.1 schema-related operations (e.g. defining or testing the structure of the data). Most obvious uses of ASN.1 schema is to guide serialisation codecs whilst encoding/decoding serialised ASN.1 contents. The PyASN1 value objects can **additionally** participate in many operations involving regular Python objects (e.g. arithmetic, comprehension etc). )rrCr0s rrUzSimpleAsn1Type.isValue=s8寋'))rc 螈|tur |s|S|j}|j}|||j|fi|S)a`Create a modified version of |ASN.1| schema or value object. The `clone()` method accepts the same set arguments as |ASN.1| class takes on instantiation except that all arguments of the `clone()` method are optional. Whatever arguments are supplied, they are used to create a copy of `self` taking precedence over the ones used to instantiate `self`. Note ---- Due to the immutable nature of the |ASN.1| object, if no arguments are supplied, no new |ASN.1| object will be created and `self` will be returned instead. )rCrr&copyr rd)r$r,r% initializerss rclonezSimpleAsn1Type.clone[sd 旼    擪圗攠))++ 楩###坱寏榚44爘444rc 鬆|tur |s|S|j}|j}|dd}||j||d<|dd}||j||d<|D]\}}||xx|z cc<|j |fi|S)aCreate a specialization of |ASN.1| schema or value object. The subtype relationship between ASN.1 types has no correlation with subtype relationship between Python types. ASN.1 type is mainly identified by its tag(s) (:py:class:`~pyasn1.type.tag.TagSet`) and value range constraints (:py:class:`~pyasn1.type.constraint.ConstraintsIntersection`). These ASN.1 type properties are implemented as |ASN.1| attributes. The `subtype()` method accepts the same set arguments as |ASN.1| class takes on instantiation except that all parameters of the `subtype()` method are optional. With the exception of the arguments described below, the rest of supplied arguments they are used to create a copy of `self` taking precedence over the ones used to instantiate `self`. The following arguments to `subtype()` create a ASN.1 subtype out of |ASN.1| type: Other Parameters ---------------- implicitTag: :py:class:`~pyasn1.type.tag.Tag` Implicitly apply given ASN.1 tag object to `self`'s :py:class:`~pyasn1.type.tag.TagSet`, then use the result as new object's ASN.1 tag(s). explicitTag: :py:class:`~pyasn1.type.tag.Tag` Explicitly apply given ASN.1 tag object to `self`'s :py:class:`~pyasn1.type.tag.TagSet`, then use the result as new object's ASN.1 tag(s). subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Add ASN.1 constraints object to one of the `self`'s, then use the result as new object's ASN.1 constraints. Returns ------- : new instance of |ASN.1| schema or value object Note ---- Due to the immutable nature of the |ASN.1| object, if no arguments are supplied, no new |ASN.1| object will be created and `self` will be returned instead. implicitTagNr explicitTag) rCrr&rpopr tagImplicitly tagExplicitlyrrd)r$r,r%rrrargoptions rsubtypezSimpleAsn1Type.subtypevs館 旼    擪圗攠))++ 梛抝55  "%)%>%>竰%K%K圠 "梛抝55  "%)%>%>竰%K%K圠 "!<<>> ( (塊圕     '    坱寏榚44爘444rc|Srrr$r,s rrzSimpleAsn1Type.prettyIns rc t|Sr)rrs r prettyOutzSimpleAsn1Type.prettyOuts5墇寊rrc6||jSr)rrrHs rr/zSimpleAsn1Type.prettyPrints弤妦榙渒***rc.|jd|jjS)Nz -> )rrdrrHs rprettyPrintTypezSimpleAsn1Type.prettyPrintTypes!淸榌榌$.*A*ABBrNrW)rrrrXrCrr'rbrrrrrrrrr\rUrrrrr/rrrrr r sa  L$    ''' $$$ $$$###$$$###$$$!!!!!!**刋*:"55556$B5B5B5B5餒++++CCCCCCrr c舐eZdZdZdZdZejZdZ dZ dZ dZ dZ d Zd Zd Zd Zd ZedZdZdZdZdZddZdZdZdZdZdS)r aBase class for all constructed classes representing ASN.1 types. ASN.1 distinguishes types by their ability to hold other objects. Those "nesting" types are known as *constructed* in ASN.1. In the user code, |ASN.1| class is normally used only for telling ASN.1 objects from others. Note ---- For as long as ASN.1 is concerned, a way to compare ASN.1 types is to use :meth:`isSameTypeWith` and :meth:`isSuperTypeOf` methods. FNc 髮|j|jd}|jdi|}||t j|fi|dS)N) componentTypesizeSpecr)rr _moveSizeSpecr rr'r#s rr'zConstructedAsn1Type.__init__sd!/   $#--爁--$++(+++++rc 髷|d|j}|r*|d|j}|r|}n||z }||d<|S)Nrr)rrr)r$r%rrs rrz!ConstructedAsn1Type._moveSizeSpecs_::榡$-88  0 **燷癉4DEE圞 (& 榵' $/團= ! rc|jjd|jrdpdd}|jD]\}}|t ur |d|d|z }|jr1|jr*|ddd|jDzz }d |zS) Nrr,rrr=rc,g|]}t|Sr)repr)rxs rrz0ConstructedAsn1Type.__repr__..s222楺恆222rr)rdrrUr&rrC componentsjoinrs rrbzConstructedAsn1Type.__repr__s 孨 # # #燭%=癵%I%I%I  =..00 < <塊圖%滸##╰╰╰癠癠";; < 4楧淥 4 .22$/22224244 4圢&&rc ||up |j|kSrrrs rrzConstructedAsn1Type.__eq__!s恥坿85 88rc|j|kSrrrs rrzConstructedAsn1Type.__ne__$%''rc|j|kSrrrs rrzConstructedAsn1Type.__lt__'&&rc|j|kSrrrs rrzConstructedAsn1Type.__le__*rrc|j|kSrrrs rrzConstructedAsn1Type.__gt__-rrc|j|kSrrrs rrzConstructedAsn1Type.__ge__0rrc*t|jSr)rrr0s rrzConstructedAsn1Type.__bool__3s怐擮$$$rc*tjdNzMethod not implementedrur0s rrzConstructedAsn1Type.components6s 8999rcdSrr)r$myClonecloneValueFlags r_cloneComponentValuesz)ConstructedAsn1Type._cloneComponentValues: rc 筘|dd}|j}|||jdi|}|r||||S)a Create a modified version of |ASN.1| schema object. The `clone()` method accepts the same set arguments as |ASN.1| class takes on instantiation except that all arguments of the `clone()` method are optional. Whatever arguments are supplied, they are used to create a copy of `self` taking precedence over the ones used to instantiate `self`. Possible values of `self` are never copied over thus `clone()` can only create a new schema object. Returns ------- : new instance of |ASN.1| type/value Note ---- Due to the mutable nature of the |ASN.1| object, even if no arguments are supplied, a new |ASN.1| object will be created and returned. rFr)rr&rr rdr)r$r%rrrs rrzConstructedAsn1Type.clone=sy. $4癳<<攠))++ 楩###....  >  & &爑╪ = = = rc 笾|j}|dd}|dd}||j||d<|dd}||j||d<|D]\}}||xx|z cc<|jdi|}|r||||S)a Create a specialization of |ASN.1| schema object. The `subtype()` method accepts the same set arguments as |ASN.1| class takes on instantiation except that all parameters of the `subtype()` method are optional. With the exception of the arguments described below, the rest of supplied arguments they are used to create a copy of `self` taking precedence over the ones used to instantiate `self`. The following arguments to `subtype()` create a ASN.1 subtype out of |ASN.1| type. Other Parameters ---------------- implicitTag: :py:class:`~pyasn1.type.tag.Tag` Implicitly apply given ASN.1 tag object to `self`'s :py:class:`~pyasn1.type.tag.TagSet`, then use the result as new object's ASN.1 tag(s). explicitTag: :py:class:`~pyasn1.type.tag.Tag` Explicitly apply given ASN.1 tag object to `self`'s :py:class:`~pyasn1.type.tag.TagSet`, then use the result as new object's ASN.1 tag(s). subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Add ASN.1 constraints object to one of the `self`'s, then use the result as new object's ASN.1 constraints. Returns ------- : new instance of |ASN.1| type/value Note ---- Due to the mutable nature of the |ASN.1| object, even if no arguments are supplied, a new |ASN.1| object will be created and returned. rFrNrrr) r&rrrrrrrdr) r$r%rrrrrrrs rrzConstructedAsn1Type.subtype`s餞攠))++ $4癳<<梛抝55  "%)%>%>竰%K%K圠 "梛抝55  "%)%>%>竰%K%K圠 "!<<>> ( (塊圕     '    ....  >  & &爑╪ = = = rc*tjdrru)r$idxs rgetComponentByPositionz*ConstructedAsn1Type.getComponentByPosition 8999rTc*tjdrru)r$rr,verifyConstraintss rsetComponentByPositionz*ConstructedAsn1Type.setComponentByPositionrrc骦t|D] \}}|||< |D] }||||<|Sr) enumerate)r$rvr%rr,ks r setComponentsz!ConstructedAsn1Type.setComponentssI#燚//  塉圕圖塈圛  圓楺攊圖塆圙 rcdSrrr0s rsetDefaultComponentsz(ConstructedAsn1Type.setDefaultComponentsrrc|jSr)rr0s rgetComponentTypez$ConstructedAsn1Type.getComponentTypes !!rc0||dSrrRr0s rverifySizeSpecz"ConstructedAsn1Type.verifySizeSpecs r)T)rrrrXstrictConstraintsrrrZrr'rrbrrrrrrrr\rrrrrrrrrrrrrr r s|   M2坺133H , , ,    ' ' '999((('''((('''(((%%%::刋:   !!!餏>>>餈:::::::   """rr )syspyasn1r pyasn1.typerrr__all__rrr Asn1ItemBaser_rCr AbstractSimpleAsn1Itemr AbstractConstructedAsn1Itemrrrr s """""" " " "%%%%%坴%%%EEEEE坸EEE餚 G7G7G7G7G7坒G7G7G7餞 '))PCPCPCPCPC怷PCPCPC餱(,ZZZZZ(ZZZ饇2rPK!j,盼$__pycache__/__init__.cpython-311.pycnu刐迭 辤;dS)Nr鷗/builddir/build/BUILD/imunify360-venv-2.6.2/opt/imunify360/venv/lib/python3.11/site-packages/pyasn1/type/__init__.pyrsrPK!雐gg!__pycache__/error.cpython-311.pycnu刐迭 辤.ddlmZGddeZdS)) PyAsn1ErrorceZdZdS)ValueConstraintErrorN)__name__ __module__ __qualname__鷔/builddir/build/BUILD/imunify360-venv-2.6.2/opt/imunify360/venv/lib/python3.11/site-packages/pyasn1/type/error.pyrr sDr rN) pyasn1.errorrrr r r r sM%$$$$$     ;     r PK!2顥$__pycache__/opentype.cpython-311.pycnu刐迭 辤- (dgZGddeZdS)OpenTypec骉eZdZdZd dZedZdZdZdZ dZ d Z d Z dS) raCreate ASN.1 type map indexed by a value The *OpenType* object models an untyped field of a constructed ASN.1 type. In ASN.1 syntax it is usually represented by the `ANY DEFINED BY` for scalars or `SET OF ANY DEFINED BY`, `SEQUENCE OF ANY DEFINED BY` for container types clauses. Typically used together with :class:`~pyasn1.type.univ.Any` object. OpenType objects duck-type a read-only Python :class:`dict` objects, however the passed `typeMap` is not copied, but stored by reference. That means the user can manipulate `typeMap` at run time having this reflected on *OpenType* object behavior. The |OpenType| class models an untyped field of a constructed ASN.1 type. In ASN.1 syntax it is usually represented by the `ANY DEFINED BY` for scalars or `SET OF ANY DEFINED BY`, `SEQUENCE OF ANY DEFINED BY` for container types clauses. Typically used with :class:`~pyasn1.type.univ.Any` type. Parameters ---------- name: :py:class:`str` Field name typeMap: :py:class:`dict` A map of value->ASN.1 type. It's stored by reference and can be mutated later to register new mappings. Examples -------- For untyped scalars: .. code-block:: python openType = OpenType( 'id', {1: Integer(), 2: OctetString()} ) Sequence( componentType=NamedTypes( NamedType('id', Integer()), NamedType('blob', Any(), openType=openType) ) ) For untyped `SET OF` or `SEQUENCE OF` vectors: .. code-block:: python openType = OpenType( 'id', {1: Integer(), 2: OctetString()} ) Sequence( componentType=NamedTypes( NamedType('id', Integer()), NamedType('blob', SetOf(componentType=Any()), openType=openType) ) ) Nc8||_| i|_dS||_dSN)_OpenType__name_OpenType__typeMap)selfnametypeMaps 鷗/builddir/build/BUILD/imunify360-venv-2.6.2/opt/imunify360/venv/lib/python3.11/site-packages/pyasn1/type/opentype.py__init__zOpenType.__init__Ks$ ?圖孨圢圢$圖孨圢圢c|jSr)rrs r r z OpenType.nameRs 寋r c4|jSr)rvaluesrs r rzOpenType.valuesXs寏$$&&&r c4|jSr)rkeysrs r rz OpenType.keys[s寏""$$$r c4|jSr)ritemsrs r rzOpenType.items^s寏##%%%r c||jvSrrrkeys r __contains__zOpenType.__contains__as恉攏$$r c|j|Srrrs r __getitem__zOpenType.__getitem__ds寏榗""r c*t|jSr)iterrrs r __iter__zOpenType.__iter__gs怐擭###r r) __name__ __module__ __qualname____doc__r propertyr rrrrrrr r rr s==饉%%%%刋 '''%%%&&&%%%###$$$$$r N)__all__objectrr%r r r(sL ,]$]$]$]$]$坴]$]$]$]$]$r PK!茊凭|4|4__pycache__/tag.cpython-311.pycnu刐迭 辤%髚ddlmZgdZdZdZdZdZdZdZdZ dZ d Z Gd d e Z Gd d e ZdZdS))error) tagClassUniversaltagClassApplicationtagClassContexttagClassPrivatetagFormatSimpletagFormatConstructedtagCategoryImplicittagCategoryExplicittagCategoryUntaggedTagTagSet锧閫槔 c螈eZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZedZedZedZdS)r aCreate ASN.1 tag Represents ASN.1 tag that can be attached to a ASN.1 type to make types distinguishable from each other. *Tag* objects are immutable and duck-type Python :class:`tuple` objects holding three integer components of a tag. Parameters ---------- tagClass: :py:class:`int` Tag *class* value tagFormat: :py:class:`int` Tag *format* value tagId: :py:class:`int` Tag ID value c螽|dkrtjd|z||_||_||_||f|_t |j|_dS)Nrz Negative tag ID (%s) not allowed)r PyAsn1Error_Tag__tagClass_Tag__tagFormat _Tag__tagId_Tag__tagClassIdhash _Tag__hash)selftagClass tagFormattagIds 鷒/builddir/build/BUILD/imunify360-venv-2.6.2/opt/imunify360/venv/lib/python3.11/site-packages/pyasn1/type/tag.py__init__z Tag.__init__9sZ 𐕏9#$F$NOO O"$ $爀極4,-- c骬d|jd|jd|jd}d|jjd|dS)N[:])rrr __class____name__rrepresentations r#__repr__z Tag.__repr__BsI 孫圤圤楾---╰瑋▅▅= 孨 # # #燸燸燸5 5r%c|j|kSNrrothers r#__eq__z Tag.__eq__H 燛))r%c|j|kSr2r3r4s r#__ne__z Tag.__ne__Kr7r%c|j|kSr2r3r4s r#__lt__z Tag.__lt__N 5((r%c|j|kSr2r3r4s r#__le__z Tag.__le__Qr7r%c|j|kSr2r3r4s r#__gt__z Tag.__gt__Tr<r%c|j|kSr2r3r4s r#__ge__z Tag.__ge__Wr7r%c|jSr2)rrs r#__hash__z Tag.__hash__Z 寋r%c骬|dkr|jS|dkr|jS|dkr|jSt)Nrrr)rrr IndexError)ridxs r# __getitem__zTag.__getitem__]s< !88? " 怉奨圶# # 怉奨圶<  r%c#驚K|jV|jV|jVdSr2)rrrrDs r#__iter__z Tag.__iter__gs7宱宭r%c髜||j|jz|j|jz|j|jzSr2r,rr rr!rr"rotherTags r#__and__z Tag.__and__l>弤妦榙渙0AA".1CC"渓╔琟;== =r%c髜||j|jz|j|jz|j|jzSr2rNrOs r#__or__z Tag.__or__qrRr%c|jS)ziASN.1 tag class Returns ------- : :py:class:`int` Tag class )rrDs r#r z Tag.tagClassvs r%c|jS)zkASN.1 tag format Returns ------- : :py:class:`int` Tag format )rrDs r#r!z Tag.tagFormat r%c|jS)zcASN.1 tag ID Returns ------- : :py:class:`int` Tag ID )rrDs r#r"z Tag.tagIds 寍r%N)r- __module__ __qualname____doc__r$r0r6r9r;r>r@rBrErJrLrQrTpropertyr r!r"r%r#r r %s2&...555 ******)))***)))*** === === 刋  刋 刋r%r c螃eZdZdZddZdZdZdZdZdZ d Z d Z d Z d Z d ZdZdZedZedZdZdZdZdZdS)raCreate a collection of ASN.1 tags Represents a combination of :class:`~pyasn1.type.tag.Tag` objects that can be attached to a ASN.1 type to make types distinguishable from each other. *TagSet* objects are immutable and duck-type Python :class:`tuple` objects holding arbitrary number of :class:`~pyasn1.type.tag.Tag` objects. Parameters ---------- baseTag: :class:`~pyasn1.type.tag.Tag` Base *Tag* object. This tag survives IMPLICIT tagging. *superTags: :class:`~pyasn1.type.tag.Tag` Additional *Tag* objects taking part in subtyping. Examples -------- .. code-block:: python class OrderNumber(NumericString): ''' ASN.1 specification Order-number ::= [APPLICATION 5] IMPLICIT NumericString ''' tagSet = NumericString.tagSet.tagImplicitly( Tag(tagClassApplication, tagFormatSimple, 5) ) orderNumber = OrderNumber('1234') r]c蟾||_||_td|D|_t ||_t |j|_dS)Nc*g|]}|j|jfSr])r r").0superTags r# z#TagSet.__init__..s" K K K癤坔 0 K K Kr%)_TagSet__baseTag_TagSet__superTagstuple_TagSet__superTagsClassIdlen_TagSet__lenOfSuperTagsr _TagSet__hash)rbaseTag superTagss r#r$zTagSet.__init__sZ $"' K K K K K# # !$營4233 r%c髣dd|jD}|rd|z}nd}d|jjd|dS)N-c驚g|]}|jd|jd|jS)r()r r!r")raxs r#rcz#TagSet.__repr__..s?#>#>#>'(23窺糩竅竅!''#R#>#>#>r%ztags untaggedr*z object, r+)joinrer,r-r.s r#r0zTagSet.__repr__sh#>#>,0,<#>#>#>??  ($爚5圢圢'圢$($;$;$;竈竈竈LLr%c:|j|jg|j|fzRSr2r,rdrerrbs r#__add__zTagSet.__add__s(坱寏榙渘N╰/?8+/MNNNNr%c:|j|jg|f|jzRSr2rtrus r#__radd__zTagSet.__radd__s(坱寏榙渘N▄窽=M/MNNNNr%c髏|jtur|j|jg|j|RS|j|Sr2)r,slicerdre)ris r#rJzTagSet.__getitem__sA ;%  !4>$.G񳷱C繟3FGGG G#燗& &r%c|j|kSr2rgr4s r#r6z TagSet.__eq__&%//r%c|j|kSr2r}r4s r#r9z TagSet.__ne__r~r%c|j|kSr2r}r4s r#r;z TagSet.__lt__&..r%c|j|kSr2r}r4s r#r>z TagSet.__le__r~r%c|j|kSr2r}r4s r#r@z TagSet.__gt__rr%c|j|kSr2r}r4s r#rBz TagSet.__ge__r~r%c|jSr2)rjrDs r#rEzTagSet.__hash__rFr%c|jSr2)rirDs r#__len__zTagSet.__len__s $$r%c|jS)z峈eturn base ASN.1 tag Returns ------- : :class:`~pyasn1.type.tag.Tag` Base tag of this *TagSet* rdrDs r#rkzTagSet.baseTags 寏r%c|jS)z甊eturn ASN.1 tags Returns ------- : :py:class:`tuple` Tuple of :class:`~pyasn1.type.tag.Tag` objects that this *TagSet* contains )rerDs r#rlzTagSet.superTagsrWr%c蟠|jtkrtjd|jt kr t |jt |j}||zS)aReturn explicitly tagged *TagSet* Create a new *TagSet* representing callee *TagSet* explicitly tagged with passed tag(s). With explicit tagging mode, new tags are appended to existing tag(s). Parameters ---------- superTag: :class:`~pyasn1.type.tag.Tag` *Tag* object to tag this *TagSet* Returns ------- : :class:`~pyasn1.type.tag.TagSet` New *TagSet* object z"Can't tag with UNIVERSAL class tag)r rrrr!r r r"rus r# tagExplicitlyzTagSet.tagExplicitlysU"   1 1 1#$HII I  !5 5 58,.B繦腘SS圚恏r%c髝|jr+t|j|jdj|j}|dd|zS)aReturn implicitly tagged *TagSet* Create a new *TagSet* representing callee *TagSet* implicitly tagged with passed tag(s). With implicit tagging mode, new tag(s) replace the last existing tag. Parameters ---------- superTag: :class:`~pyasn1.type.tag.Tag` *Tag* object to tag this *TagSet* Returns ------- : :class:`~pyasn1.type.tag.TagSet` New *TagSet* object N)rer r r!r"rus r# tagImplicitlyzTagSet.tagImplicitlysD"   ^8,╠.>竢.B.L萮蘮]]圚怌怰怌寉8##r%c骹t||jkrdS|j|d|jkS)aTest type relationship against given *TagSet* The callee is considered to be a supertype of given *TagSet* tag-wise if all tags in *TagSet* are present in the callee and they are in the same order. Parameters ---------- tagSet: :class:`~pyasn1.type.tag.TagSet` *TagSet* object to evaluate against the callee Returns ------- : :py:class:`bool` :obj:`True` if callee is a supertype of *tagSet* FN)rhrire)rtagSets r#isSuperTagSetOfzTagSet.isSuperTagSetOf4s9" 坴;;. . .56*@4+@*@#AAAr%c|jSr2rrDs r# getBaseTagzTagSet.getBaseTagKs 寏r%N)r])r-rYrZr[r$r0rvrxrJr6r9r;r>r@rBrErr\rkrlrrrrr]r%r#rrse!!餌4444MMMOOOOOO''' 000000///000///000%%%刋  刋 .$$$*BBB.r%rc"t||Sr2)r)tags r# initTagSetrNs #恠  r%N)pyasn1r__all__rrrrrr r r r objectr rrr]r%r#rs 3 3 3 ppppp&ppp餱ttttt圴ttt餷r%PK!|莂cac%__pycache__/namedtype.cpython-311.pycnu刐迭 辤3?螵ddlZddlmZddlmZddlmZgdZGddeZGdd eZ Gd d eZ Gd d eZ dS)N)error)tag)tagmap) NamedTypeOptionalNamedTypeDefaultedNamedType NamedTypesc蟋eZdZdZdZdZddZdZdZdZ dZ d Z d Z d Z d Zd ZdZedZedZedZdZdZdS)raCreate named field object for a constructed ASN.1 type. The |NamedType| object represents a single name and ASN.1 type of a constructed ASN.1 type. |NamedType| objects are immutable and duck-type Python :class:`tuple` objects holding *name* and *asn1Object* components. Parameters ---------- name: :py:class:`str` Field name asn1Object: ASN.1 type object FNc驜||_||_||f|_||_dSN)_NamedType__name_NamedType__type_NamedType__nameAndType_NamedType__openType)selfname asn1ObjectopenTypes 鷘/builddir/build/BUILD/imunify360-venv-2.6.2/opt/imunify360/venv/lib/python3.11/site-packages/pyasn1/type/namedtype.py__init__zNamedType.__init__#s(   !:-"c髍|jd|j}|jr |d|jzz }d|jjd|dS)N=z, open type %r)rrr __class____name__rrepresentations r__repr__zNamedType.__repr__)sS$(營營╰? = ? .> >圢 孨 # # #燸燸燸5 5rc|j|kSr rrothers r__eq__zNamedType.__eq__2!燯**rc|j|kSr r"r#s r__ne__zNamedType.__ne__5r&rc|j|kSr r"r#s r__lt__zNamedType.__lt__8!燛))rc|j|kSr r"r#s r__le__zNamedType.__le__;r&rc|j|kSr r"r#s r__gt__zNamedType.__gt__>r+rc|j|kSr r"r#s r__ge__zNamedType.__ge__Ar&rc*t|jSr )hashrrs r__hash__zNamedType.__hash__D怐&'''rc|j|Sr r"ridxs r __getitem__zNamedType.__getitem__Gs!#&&rc*t|jSr )iterrr4s r__iter__zNamedType.__iter__Jr6rc|jSr )r r4s rrzNamedType.nameM 寋rc|jSr )rr4s rrzNamedType.asn1ObjectQr?rc|jSr )rr4s rrzNamedType.openTypeUs rc|jSr rr4s rgetNamezNamedType.getName[s 寉rc|jSr rr4s rgetTypezNamedType.getType^s rr )r __module__ __qualname____doc__ isOptional isDefaultedrr r%r(r*r-r/r1r5r:r=propertyrrrrDrGrrrrsCJK#### 555++++++***+++***+++((('''(((刋刋刋 rrc eZdZejZdZdS)rTN)rrHrIrrJrKrNrrrrbsGJJJrrc eZdZejZdZdS)rTN)rrHrIrrJrLrNrrrrhsGKKKrrc髒eZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZGddeZdZdZdZdZdZdZdZdZdZ dZ!e"d Z#d!Z$e"d"Z%e"d#Z&e"d$Z'e"d%Z(e"d&Z)e"d'Z*d(S))r a+Create a collection of named fields for a constructed ASN.1 type. The NamedTypes object represents a collection of named fields of a constructed ASN.1 type. *NamedTypes* objects are immutable and duck-type Python :class:`dict` objects holding *name* as keys and ASN.1 type object as values. Parameters ---------- *namedTypes: :class:`~pyasn1.type.namedtype.NamedType` Examples -------- .. code-block:: python class Description(Sequence): ''' ASN.1 specification: Description ::= SEQUENCE { surname IA5String, first-name IA5String OPTIONAL, age INTEGER DEFAULT 40 } ''' componentType = NamedTypes( NamedType('surname', IA5String()), OptionalNamedType('first-name', IA5String()), DefaultedNamedType('age', Integer(40)) ) descr = Description() descr['surname'] = 'Smith' descr['first-name'] = 'John' c驞||_t|j|_||_||_||_d|vr| pi|_ | d|_ | d|_ td|jD|_td|jD|_t#dt%|jD|_t#d|jD|_t+d |jD|_t+d |jD|_dS) NterminalT)uniqueFc.g|]}|js|jdST)rLrK.0 namedTypes r z'NamedTypes.__init__..sB+]+]+]癐.7.C+]谿P訥[+]4+]+]+]rc g|] }|j d SrV)rrWs rrZz'NamedTypes.__init__..s/#:#:#:↖&/&8#:4#:#:#:rc4g|]\}}|j |j|SrN)rKrL)rXr9nts rrZz'NamedTypes.__init__..s,mmm榖 m衈`証lmmmmrcg|] }|j SrNrCrWs rrZz'NamedTypes.__init__..s S S S癐 S S Srcg|] }|j SrNrFrWs rrZz'NamedTypes.__init__..sWWW 榶3WWWrc*g|]}|j|jfSrN)rrrWs rrZz'NamedTypes.__init__..s"hhh榶渵▂/CDhhhr)_NamedTypes__namedTypeslen_NamedTypes__namedTypesLen_NamedTypes__computeMinTagSet_NamedTypes__minTagSet _NamedTypes__computeNameToPosMap_NamedTypes__nameToPosMap_NamedTypes__computeTagToPosMap_NamedTypes__tagToPosMap"_NamedTypes__computeAmbiguousTypes_NamedTypes__ambiguousTypes_NamedTypes__computeTagMaps_NamedTypes__uniqueTagMap_NamedTypes__nonUniqueTagMapany!_NamedTypes__hasOptionalOrDefault_NamedTypes__hasOpenTypes frozenset enumerate_NamedTypes__requiredComponents_NamedTypes__keystuple_NamedTypes__values_NamedTypes__items)r namedTypeskwargss rrzNamedTypes.__init__s&"4#4552244"88::!6688 *& 8 [窽=Y=Y=[=[ a衉a"3343@@!%!6!6竐!6!D!D&)+]+]訟R+]+]+]'^'^#!#:#:9J#:#:#:;;%.mm╠.?$@$@mmm%%! S S訟R S S STT WW繲訣VWWWXX hh蠽Z訴ghhhii rc髉dd|jD}d|jjd|dS)Nz, cg|]}d|zS)z%rrNrXxs rrZz'NamedTypes.__repr__..s#H#H#H燚1#H#H#Hrrz object, types r)joinrarrrs rr zNamedTypes.__repr__sE#H#H癲6G#H#H#HII 孨 # # #燸燸燸5 5rc|j|kSr rar#s rr%zNamedTypes.__eq__ 燛))rc|j|kSr rr#s rr(zNamedTypes.__ne__rrc|j|kSr rr#s rr*zNamedTypes.__lt__ 5((rc|j|kSr rr#s rr-zNamedTypes.__le__rrc|j|kSr rr#s rr/zNamedTypes.__gt__rrc|j|kSr rr#s rr1zNamedTypes.__ge__rrc*t|jSr )r3rar4s rr5zNamedTypes.__hash__s怐%&&&rc髇 |j|S#t$r|j|j|cYSwxYwr )ra TypeErrorrgr8s rr:zNamedTypes.__getitem__sL ?$燬) ) ? ? ?$燭%8%=> > > > ?鴖 "44c||jvSr )rg)rkeys r __contains__zNamedTypes.__contains__s恉)))rc$d|jDS)Nc3&K|] }|dV dS)rNrNr}s r z&NamedTypes.__iter__..s&00!000000rrr4s rr=zNamedTypes.__iter__s00榙/0000rc|jdkS)Nrrcr4s r__bool__zNamedTypes.__bool__s#燼''rc|jSr rr4s r__len__zNamedTypes.__len__s ##rc|jSr )rwr4s rvalueszNamedTypes.valuess 寎rc|jSr )rur4s rkeyszNamedTypes.keyss 寋rc|jSr )rxr4s ritemszNamedTypes.itemss 寍rc |j|jSr )rrar4s rclonezNamedTypes.clones坱寏榯011rceZdZdZdZdS)NamedTypes.PostponedErrorc||_dSr )_PostponedError__errorMsg)rerrorMsgs rrz"NamedTypes.PostponedError.__init__s &圖孫圤圤rc4tj|jr )r PyAsn1Errorr)ritems rr:z%NamedTypes.PostponedError.__getitem__s$燭55 5rN)rrHrIrr:rNrrPostponedErrorrs2 ' ' ' 6 6 6 6 6rrci}t|jD]i\}}|jj}t |t jr|cS|s2|jD]/}||vr$t d|d|ccS|||<0宩|S)NzDuplicate component tag  at )rsrartagMap isinstancer r presentTypes)r tagToPosMapr9rYr_tagSets r__computeTagToPosMapzNamedTypes.__computeTagToPosMaps '(9:: + +塏圕)0團&*";<<   !. + +榢))%444衃b衃b衃b衐m衐m5nooooooo'* 楪$$ + rc蟛i}t|jD]?\}}|j|vr'td|jd|cS|||j<孈|S)NzDuplicate component name r)rsrarr r)r nameToPosMapr9rYs r__computeNameToPosMapz NamedTypes.__computeNameToPosMapsw '(9:: / /塏圕寏--!000蠿a訶f蠿f蠿f衕q衕q1rsssss+.圠 ( (rc6i}d}ttt|jD]e\}}|js|jr|f|z}n|f}t |t |jkr|||<孒t|itd||<宖|S)NrNT)rS) reversedrvrsrarKrLrbr dict)rambiguousTypespartialAmbiguousTypesr9rYs r__computeAmbiguousTypesz"NamedTypes.__computeAmbiguousTypess "&璝皌7H-I-I'J'JKK ` `塏圕# 5爕'< 5)2 7L(L%%)2 %())璖1B-C-CCC&*榮##&02G&_4衁]蠯^袺^訩^&_&_榮##rc髄 |j|jS#t$rtjdwxYw)aTReturn ASN.1 type object by its position in fields set. Parameters ---------- idx: :py:class:`int` Field index Returns ------- : ASN.1 type Raises ------ ~pyasn1.error.PyAsn1Error If given position is out of fields range Type position out of range)rar IndexErrorrrr8s rgetTypeByPositionzNamedTypes.getTypeByPositionsJ$ B$燬)4 4 B B B#$@AA A B3c骿 |j|S#t$rtjd|dwxYw)aReturn field position by its ASN.1 type. Parameters ---------- tagSet: :class:`~pysnmp.type.tag.TagSet` ASN.1 tag set distinguishing one ASN.1 type from others. Returns ------- : :py:class:`int` ASN.1 type position in fields set Raises ------ ~pyasn1.error.PyAsn1Error If *tagSet* is not present or ASN.1 types are not unique within callee *NamedTypes* zType not found)riKeyErrorrr)rtagSets rgetPositionByTypezNamedTypes.getPositionByType(sP$ E%爁- - E E E##򍁴6$CDD D E #2c髄 |j|jS#t$rtjdwxYw)anReturn field name by its position in fields set. Parameters ---------- idx: :py:class:`idx` Field index Returns ------- : :py:class:`str` Field name Raises ------ ~pyasn1.error.PyAsn1Error If given field name is not present in callee *NamedTypes* r)rarrrrr8s rgetNameByPositionzNamedTypes.getNameByPosition@sJ$ B$燬). . B B B#$@AA A B鴕c骿 |j|S#t$rtjd|dwxYw)a|Return field position by filed name. Parameters ---------- name: :py:class:`str` Field name Returns ------- : :py:class:`int` Field position in fields set Raises ------ ~pyasn1.error.PyAsn1Error If *name* is not present or not unique within callee *NamedTypes* zName r)rgrrr)rrs rgetPositionByNamezNamedTypes.getPositionByNameXsP$ C&爐, , C C C##򌚚4$ABB B C鴕c髄 |j|jS#t$rtjdwxYw)aReturn ASN.1 types that are allowed at or past given field position. Some ASN.1 serialisation allow for skipping optional and defaulted fields. Some constructed ASN.1 types allow reordering of the fields. When recovering such objects it may be important to know which types can possibly be present at any given position in the field sets. Parameters ---------- idx: :py:class:`int` Field index Returns ------- : :class:`~pyasn1.type.tagmap.TagMap` Map if ASN.1 types allowed at given field position Raises ------ ~pyasn1.error.PyAsn1Error If given position is out of fields range r)rkrrrrr8s rgetTagMapNearPositionz NamedTypes.getTagMapNearPositionpsJ. B(-4 4 B B B#$@AA A B鴕c髱 ||j||zS#t$rtjdwxYw)aReturn the closest field position where given ASN.1 type is allowed. Some ASN.1 serialisation allow for skipping optional and defaulted fields. Some constructed ASN.1 types allow reordering of the fields. When recovering such objects it may be important to know at which field position, in field set, given *tagSet* is allowed at or past *idx* position. Parameters ---------- tagSet: :class:`~pyasn1.type.tag.TagSet` ASN.1 type which field position to look up idx: :py:class:`int` Field position at or past which to perform ASN.1 type look up Returns ------- : :py:class:`int` Field position in fields set Raises ------ ~pyasn1.error.PyAsn1Error If *tagSet* is not present or not unique within callee *NamedTypes* or *idx* is out of fields range r)rkrrrr)rrr9s rgetPositionNearTypezNamedTypes.getPositionNearTypesZ6 B.╯3EE纅MMM M B B B#$@AA A B鴖 "%Ac螃d}|jD]3}|j} |j}n#t$r |j}YnwxYw|||kr|}4|pt jSr )rar minTagSetAttributeErrorrrTagSet)rrrYrrs r__computeMinTagSetzNamedTypes.__computeMinTagSets * # #圛"-圝 +#-! + + +#* + 燜╕$6$6" (滳淛橪淟(s 00c|jS)aReturn the minimal TagSet among ASN.1 type in callee *NamedTypes*. Some ASN.1 types/serialisation protocols require ASN.1 types to be arranged based on their numerical tag value. The *minTagSet* property returns that. Returns ------- : :class:`~pyasn1.type.tagset.TagSet` Minimal TagSet among ASN.1 types in callee *NamedTypes* )rer4s rrzNamedTypes.minTagSets rc 螽i}i}d}|jD]瞹|jj}t|tjr|cS|D]9}|r+||vr'td|d|d|ccS|j||<:||j||j}寣|jtd|cS尦tj |||S)NzNon-unique tagSet z of rz Duplicate default ASN.1 type at ) rarrrr rupdate skipTypes defaultTyperTagMap)rrTrrrrYrrs r__computeTagMapszNamedTypes.__computeTagMapss+   * a a圛)0團&*";<<    < <u榝 44%444衃a衃a衃a衏l衏l衏l衝r衝r5sttttttt'0'; 榁$$   榁- . . ."$0 #/!000衁]衁]1_`````0寎榎9発BBBrc|jS)aReturn a *TagMap* object from tags and types recursively. Return a :class:`~pyasn1.type.tagmap.TagMap` object by combining tags from *TagMap* objects of children types and associating them with their immediate child type. Example ------- .. code-block:: python OuterType ::= CHOICE { innerType INTEGER } Calling *.tagMap* on *OuterType* will yield a map like this: .. code-block:: python Integer.tagSet -> Choice )rnr4s rrzNamedTypes.tagMaps ,%%rc|jS)aReturn a *TagMap* object from unique tags and types recursively. Return a :class:`~pyasn1.type.tagmap.TagMap` object by combining tags from *TagMap* objects of children types and associating them with their immediate child type. Example ------- .. code-block:: python OuterType ::= CHOICE { innerType INTEGER } Calling *.tagMapUnique* on *OuterType* will yield a map like this: .. code-block:: python Integer.tagSet -> Choice Note ---- Duplicate *TagSet* objects found in the tree of children types would cause error. )rmr4s r tagMapUniquezNamedTypes.tagMapUniques 8""rc|jSr )rpr4s rhasOptionalOrDefaultzNamedTypes.hasOptionalOrDefaults **rc|jSr )rqr4s r hasOpenTypeszNamedTypes.hasOpenTypess ""rc*t|jSr )rvrar4s rryzNamedTypes.namedTypes s怲&'''rc|jSr )rtr4s rrequiredComponentszNamedTypes.requiredComponents$s ((rN)+rrHrIrJrr r%r(r*r-r/r1r5r:rr=rrrrrrobjectrrhrfrjrrrrrrrdrMrrlrrrrryrrNrrr r ns##餒jjj*555 ******)))***)))***'''???***111((($$$ 22266666666      BBB0EEE0BBB0CCC0BBB:BBB養)))    刋  CCC*&&刋&.##刋#:++刋+##刋#((刋())刋)))rr ) syspyasn1r pyasn1.typerr__all__rrrrr rNrrrs    OOOOOOOO餯   x)x)x)x)x)x)x)x)x)x)rPK!4譏紆紆&__pycache__/constraint.cpython-311.pycnu刐迭 辤沀螵ddlZddlmZgdZGddeZGddeZGdd eZGd d eZGd d eZ GddeZ GddeZ GddeZ GddeZ GddeZGddeZGddeZGddeZGddeZdS) N)error) SingleValueConstraintContainedSubtypeConstraintValueRangeConstraintValueSizeConstraintPermittedAlphabetConstraintInnerTypeConstraintConstraintsExclusionConstraintsIntersectionConstraintsUnionc髉eZdZdZddZdZdZdZdZdZ d Z d Z d Z d Z d ZdZdZdZdZdS)AbstractConstraintc鬆t|_||t|jj|jf|_dSN)set _valueMap _setValueshash __class____name___values_AbstractConstraint__hashselfvaluess 鷙/builddir/build/BUILD/imunify360-venv-2.6.2/opt/imunify360/venv/lib/python3.11/site-packages/pyasn1/type/constraint.py__init__zAbstractConstraint.__init__s> 楧淣3癟碶BCC Nc螃|jsdS |||dS#tj$r}tj|d|d}~wwxYw)Nz failed at: )r _testValuerValueConstraintError)rvalueidxexcs r__call__zAbstractConstraint.__call__su寍  團  廜奜楨3 ' ' ' ' ')   ,&*燿燿––0  鴖#AA  Ac髮d|jjz}|jr*|ddd|jDzz }d|zS)Nz %s objectz , consts %sz, c,g|]}t|S)repr).0xs r z/AbstractConstraint.__repr__..,s///楺恆///rz<%s>)rrrjoin)rrepresentations r__repr__zAbstractConstraint.__repr__'s\$(?@ < 1 榤╠痠猧//$,////1/11 1圢&&rc$||urdS|j|kS)NTrrothers r__eq__zAbstractConstraint.__eq__0s 5==4寍榰$$rc|j|kSrr1r2s r__ne__zAbstractConstraint.__ne__5寍榰$$rc|j|kSrr1r2s r__lt__zAbstractConstraint.__lt__8寍榚##rc|j|kSrr1r2s r__le__zAbstractConstraint.__le__;r7rc|j|kSrr1r2s r__gt__zAbstractConstraint.__gt__>r:rc|j|kSrr1r2s r__ge__zAbstractConstraint.__ge__Ar7rc*t|jSr)boolrrs r__bool__zAbstractConstraint.__bool__D怐擫!!!rc|jSr)rrCs r__hash__zAbstractConstraint.__hash__Gs 寋rc||_dSrr1rs rrzAbstractConstraint._setValuesJs  rc*tj|rrr!rr"r#s rr zAbstractConstraint._testValueMs(///rc|jSrrrCs r getValueMapzAbstractConstraint.getValueMapQs 寏rc驲||up#|j p||kp||vSr)rrNrotherConstraints r isSuperTypeOfz AbstractConstraint.isSuperTypeOfTsD4'6擫 64'633555 7rc.||up| p||kp||jvSrrMrPs r isSubTypeOfzAbstractConstraint.isSubTypeOf[s74'224'2 4>1 3rr)r __module__ __qualname__rr%r/r4r6r9r<r>r@rDrGrr rNrRrTr(rrrrs DDD    '''%%% %%%$$$%%%$$$%%%"""00077733333rrc6eZdZdZdZdZdZdZdZdZ dS) raCreate a SingleValueConstraint object. The SingleValueConstraint satisfies any value that is present in the set of permitted values. Objects of this type are iterable (emitting constraint values) and can act as operands for some arithmetic operations e.g. addition and subtraction. The latter can be used for combining multiple SingleValueConstraint objects into one. The SingleValueConstraint object can be applied to any ASN.1 type. Parameters ---------- *values: :class:`int` Full set of values permitted by this constraint object. Examples -------- .. code-block:: python class DivisorOfSix(Integer): ''' ASN.1 specification: Divisor-Of-6 ::= INTEGER (1 | 2 | 3 | 6) ''' subtypeSpec = SingleValueConstraint(1, 2, 3, 6) # this will succeed divisor_of_six = DivisorOfSix(1) # this will raise ValueConstraintError divisor_of_six = DivisorOfSix(7) c<||_t||_dSrrr_setrs rrz SingleValueConstraint._setValues 慘擪 rc驚||jvrtj|dSr)rZrr!rKs rr z SingleValueConstraint._testValues(  ! !,║33 3 " !rc||jvSr)rZ)ritems r __contains__z"SingleValueConstraint.__contains__s恡攜  rc*t|jSr)iterrZrCs r__iter__zSingleValueConstraint.__iter__s怐擨rc驠|j|j|Sr)rrZunionr constraints r__add__zSingleValueConstraint.__add__s坱寏  ; ;==rc驠|j|j|Sr)rrZ differenceres r__sub__zSingleValueConstraint.__sub__s!坱寏 4 4癦 @ @BBrN) rrUrV__doc__rr r_rbrgrjr(rrrrbs~##餒   444 !!!>>>CCCCCrrceZdZdZdZdS)raCreate a ContainedSubtypeConstraint object. The ContainedSubtypeConstraint satisfies any value that is present in the set of permitted values and also satisfies included constraints. The ContainedSubtypeConstraint object can be applied to any ASN.1 type. Parameters ---------- *values: Full set of values and constraint objects permitted by this constraint object. Examples -------- .. code-block:: python class DivisorOfEighteen(Integer): ''' ASN.1 specification: Divisors-of-18 ::= INTEGER (INCLUDES Divisors-of-6 | 9 | 18) ''' subtypeSpec = ContainedSubtypeConstraint( SingleValueConstraint(1, 2, 3, 6), 9, 18 ) # this will succeed divisor_of_eighteen = DivisorOfEighteen(9) # this will raise ValueConstraintError divisor_of_eighteen = DivisorOfEighteen(10) c髽|jD]A}t|tr |||$||jvrt j|孊dSr)r isinstancerrZrr!rr"r#rfs rr z%ContainedSubtypeConstraint._testValuesh, 8 8圝*&899 8 5#&&&&榙渋''0777( 8 8rNrrUrVrkr r(rrrrs.""餏88888rrceZdZdZdZdZdS)ra{Create a ValueRangeConstraint object. The ValueRangeConstraint satisfies any value that falls in the range of permitted values. The ValueRangeConstraint object can only be applied to :class:`~pyasn1.type.univ.Integer` and :class:`~pyasn1.type.univ.Real` types. Parameters ---------- start: :class:`int` Minimum permitted value in the range (inclusive) end: :class:`int` Maximum permitted value in the range (inclusive) Examples -------- .. code-block:: python class TeenAgeYears(Integer): ''' ASN.1 specification: TeenAgeYears ::= INTEGER (13 .. 19) ''' subtypeSpec = ValueRangeConstraint(13, 19) # this will succeed teen_year = TeenAgeYears(18) # this will raise ValueConstraintError teen_year = TeenAgeYears(20) c骦||jks ||jkrtj|dSr)startstoprr!rKs rr zValueRangeConstraint._testValues4 4:  !2!2,║33 3"3!2rc驜t|dkr!tj|jjd|\|_|_|j|jkr0tj|jjd|jd|jt||dS)Nz: bad constraint valuesz,: screwed constraint values (start > stop): z > ) lenr PyAsn1Errorrrrsrtrrrs rrzValueRangeConstraint._setValuess 坴;;!  #/3瑍/F/F/FH !' 怐擨 : ! !#擭+++擩怞怞   %%燿‵33333rNrrUrVrkr rr(rrrrs=""餏444 4 4 4 4 4rrceZdZdZdZdS)raCreate a ValueSizeConstraint object. The ValueSizeConstraint satisfies any value for as long as its size falls within the range of permitted sizes. The ValueSizeConstraint object can be applied to :class:`~pyasn1.type.univ.BitString`, :class:`~pyasn1.type.univ.OctetString` (including all :ref:`character ASN.1 types `), :class:`~pyasn1.type.univ.SequenceOf` and :class:`~pyasn1.type.univ.SetOf` types. Parameters ---------- minimum: :class:`int` Minimum permitted size of the value (inclusive) maximum: :class:`int` Maximum permitted size of the value (inclusive) Examples -------- .. code-block:: python class BaseballTeamRoster(SetOf): ''' ASN.1 specification: BaseballTeamRoster ::= SET SIZE (1..25) OF PlayerNames ''' componentType = PlayerNames() subtypeSpec = ValueSizeConstraint(1, 25) # this will succeed team = BaseballTeamRoster() team.extend(['Jan', 'Matej']) encode(team) # this will raise ValueConstraintError team = BaseballTeamRoster() team.extend(['Jan'] * 26) encode(team) Note ---- Whenever ValueSizeConstraint is applied to mutable types (e.g. :class:`~pyasn1.type.univ.SequenceOf`, :class:`~pyasn1.type.univ.SetOf`), constraint validation only happens at the serialisation phase rather than schema instantiation phase (as it is with immutable types). c髕t|}||jks ||jkrtj|dSr)rwrsrtrr!)rr"r# valueSizes rr zValueSizeConstraint._testValue8s?慗擩 恡攝 ! !燳%:%:,║33 3&;%:rNrpr(rrrrs.44餵44444rrceZdZdZdZdZdS)ra Create a PermittedAlphabetConstraint object. The PermittedAlphabetConstraint satisfies any character string for as long as all its characters are present in the set of permitted characters. Objects of this type are iterable (emitting constraint values) and can act as operands for some arithmetic operations e.g. addition and subtraction. The PermittedAlphabetConstraint object can only be applied to the :ref:`character ASN.1 types ` such as :class:`~pyasn1.type.char.IA5String`. Parameters ---------- *alphabet: :class:`str` Full set of characters permitted by this constraint object. Example ------- .. code-block:: python class BooleanValue(IA5String): ''' ASN.1 specification: BooleanValue ::= IA5String (FROM ('T' | 'F')) ''' subtypeSpec = PermittedAlphabetConstraint('T', 'F') # this will succeed truth = BooleanValue('T') truth = BooleanValue('TF') # this will raise ValueConstraintError garbage = BooleanValue('TAF') ASN.1 `FROM ... EXCEPT ...` clause can be modelled by combining multiple PermittedAlphabetConstraint objects into one: Example ------- .. code-block:: python class Lipogramme(IA5String): ''' ASN.1 specification: Lipogramme ::= IA5String (FROM (ALL EXCEPT ("e"|"E"))) ''' subtypeSpec = ( PermittedAlphabetConstraint(*string.printable) - PermittedAlphabetConstraint('e', 'E') ) # this will succeed lipogramme = Lipogramme('A work of fiction?') # this will raise ValueConstraintError lipogramme = Lipogramme('Eel') Note ---- Although `ConstraintsExclusion` object could seemingly be used for this purpose, practically, for it to work, it needs to represent its operand constraints as sets and intersect one with the other. That would require the insight into the constraint values (and their types) that are otherwise hidden inside the constraint object. Therefore it's more practical to model `EXCEPT` clause at `PermittedAlphabetConstraint` level instead. c<||_t||_dSrrYrs rrz&PermittedAlphabetConstraint._setValuesr[rc骲|j|stj|dSr)rZ issupersetrr!rKs rr z&PermittedAlphabetConstraint._testValues5寉##燛** 4,║33 3 4 4rNrrUrVrkrr r(rrrr>s?II餞   44444rrceZdZdZdZdZdS)ComponentPresentConstraintaCreate a ComponentPresentConstraint object. The ComponentPresentConstraint is only satisfied when the value is not `None`. The ComponentPresentConstraint object is typically used with `WithComponentsConstraint`. Examples -------- .. code-block:: python present = ComponentPresentConstraint() # this will succeed present('whatever') # this will raise ValueConstraintError present(None) c驚d|_|rtjddS)N)zNo arguments expectedrrrxrs rrz%ComponentPresentConstraint._setValuess--  =#$;<< < = =rc2|tjddS)NzComponent is not present:rJrKs rr z%ComponentPresentConstraint._testValues& =,+-- - =rNrr(rrrrs<(=== -----rrceZdZdZdZdZdS)ComponentAbsentConstraintaCreate a ComponentAbsentConstraint object. The ComponentAbsentConstraint is only satisfied when the value is `None`. The ComponentAbsentConstraint object is typically used with `WithComponentsConstraint`. Examples -------- .. code-block:: python absent = ComponentAbsentConstraint() # this will succeed absent(None) # this will raise ValueConstraintError absent('whatever') c驚d|_|rtjddS)N)zrrrs rrz$ComponentAbsentConstraint._setValuess-,  =#$;<< < = =rc8|tjd|zdS)NzComponent is not absent: %rrJrKs rr z$ComponentAbsentConstraint._testValues-  ,-577 7  rNrr(rrrrs<(=== 77777rrceZdZdZdZdZdS)WithComponentsConstrainta& Create a WithComponentsConstraint object. The `WithComponentsConstraint` satisfies any mapping object that has constrained fields present or absent, what is indicated by `ComponentPresentConstraint` and `ComponentAbsentConstraint` objects respectively. The `WithComponentsConstraint` object is typically applied to :class:`~pyasn1.type.univ.Set` or :class:`~pyasn1.type.univ.Sequence` types. Parameters ---------- *fields: :class:`tuple` Zero or more tuples of (`field`, `constraint`) indicating constrained fields. Notes ----- On top of the primary use of `WithComponentsConstraint` (ensuring presence or absence of particular components of a :class:`~pyasn1.type.univ.Set` or :class:`~pyasn1.type.univ.Sequence`), it is also possible to pass any other constraint objects or their combinations. In case of scalar fields, these constraints will be verified in addition to the constraints belonging to scalar components themselves. However, formally, these additional constraints do not change the type of these ASN.1 objects. Examples -------- .. code-block:: python class Item(Sequence): # Set is similar ''' ASN.1 specification: Item ::= SEQUENCE { id INTEGER OPTIONAL, name OCTET STRING OPTIONAL } WITH COMPONENTS id PRESENT, name ABSENT | id ABSENT, name PRESENT ''' componentType = NamedTypes( OptionalNamedType('id', Integer()), OptionalNamedType('name', OctetString()) ) withComponents = ConstraintsUnion( WithComponentsConstraint( ('id', ComponentPresentConstraint()), ('name', ComponentAbsentConstraint()) ), WithComponentsConstraint( ('id', ComponentAbsentConstraint()), ('name', ComponentPresentConstraint()) ) ) item = Item() # This will succeed item['id'] = 1 # This will succeed item.reset() item['name'] = 'John' # This will fail (on encoding) item.reset() descr['id'] = 1 descr['name'] = 'John' c骪|jD]#\}}|||$dSr)rget)rr"r#fieldrfs rr z#WithComponentsConstraint._testValuesA!% ) ) 圗: 圝恥梱抷'' ( ( ( ( ) )rc<t||dSrrrrs rrz#WithComponentsConstraint._setValues%%燿‵33333rNryr(rrrrs?EE餖)))44444rrceZdZdZdZdZdS)r z4Value must satisfy the type and presence constraintsc篪|jr||dS|jrT||jvrtj||j|\}}|dkrtj|||dSdS)NABSENT)*_InnerTypeConstraint__singleTypeConstraint,_InnerTypeConstraint__multipleTypeConstraintrr!)rr"r#rfstatuss rr zInnerTypeConstraint._testValue's  &   ' ' . . . . .  * $7770777!%!>竤!C 圝!!0777 圝恥        rc筘i|_d|_|D]=}t|tr|d|df|j|d<6||_>t||dS)Nrvr)rrrntuplerr)rrvs rrzInnerTypeConstraint._setValues2sz(*%&*# 0 0圓!漊## 067磀窤竌糄癹-╝琩33./++%%燿‵33333rNryr(rrr r $s8>>   44444rr ceZdZdZdZdZdS)r aCreate a ConstraintsExclusion logic operator object. The ConstraintsExclusion logic operator succeeds when the value does *not* satisfy the operand constraint. The ConstraintsExclusion object can be applied to any constraint and logic operator object. Parameters ---------- *constraints: Constraint or logic operator objects. Examples -------- .. code-block:: python class LuckyNumber(Integer): subtypeSpec = ConstraintsExclusion( SingleValueConstraint(13) ) # this will succeed luckyNumber = LuckyNumber(12) # this will raise ValueConstraintError luckyNumber = LuckyNumber(13) Note ---- The `FROM ... EXCEPT ...` ASN.1 clause should be modeled by combining constraint objects into one. See `PermittedAlphabetConstraint` for more information. c髥|jD]8} |||n#tj$rY!wxYwtj|dSrrrr!ros rr zConstraintsExclusion._testValuebsm, 4 4圝  5#&&&&-    ,║33 3 4 4s **c<t||dSrrrs rrzConstraintsExclusion._setValueslrrNryr(rrr r ?s=!!餌44444444rr c2eZdZdZdZdZdZdZdZdS)AbstractConstraintSetc|j|Srr1)rr#s r __getitem__z!AbstractConstraintSet.__getitem__rs寍楥  rc*t|jSr)rarrCs rrbzAbstractConstraintSet.__iter__urErc(|j|j|fzSrrrrr"s rrgzAbstractConstraintSet.__add__xs坱寏 ▁ 799rc(|j|f|jzSrrrs r__radd__zAbstractConstraintSet.__radd__{s坱寏4< 799rc*t|jSr)rwrrCs r__len__zAbstractConstraintSet.__len__~s4<   rc螽||_|D]J}|rF|j||j|孠dSr)rraddupdaterN)rrrfs rrz AbstractConstraintSet._setValuessh   @ @圝 @"":...%%爅&<&<&>&>??? @ @rN) rrUrVrrbrgrrrr(rrrrpss!!!"""::::::!!! @@@@@rrceZdZdZdZdS)r a7Create a ConstraintsIntersection logic operator object. The ConstraintsIntersection logic operator only succeeds if *all* its operands succeed. The ConstraintsIntersection object can be applied to any constraint and logic operator objects. The ConstraintsIntersection object duck-types the immutable container object like Python :py:class:`tuple`. Parameters ---------- *constraints: Constraint or logic operator objects. Examples -------- .. code-block:: python class CapitalAndSmall(IA5String): ''' ASN.1 specification: CapitalAndSmall ::= IA5String (FROM ("A".."Z"|"a".."z")) ''' subtypeSpec = ConstraintsIntersection( PermittedAlphabetConstraint('A', 'Z'), PermittedAlphabetConstraint('a', 'z') ) # this will succeed capital_and_small = CapitalAndSmall('Hello') # this will raise ValueConstraintError capital_and_small = CapitalAndSmall('hello') c2|jD]}|||dSrr1ros rr z"ConstraintsIntersection._testValues2, # #圝 圝恥榗 " " " " # #rNrpr(rrr r s.%%餖#####rr ceZdZdZdZdS)r aCreate a ConstraintsUnion logic operator object. The ConstraintsUnion logic operator succeeds if *at least* a single operand succeeds. The ConstraintsUnion object can be applied to any constraint and logic operator objects. The ConstraintsUnion object duck-types the immutable container object like Python :py:class:`tuple`. Parameters ---------- *constraints: Constraint or logic operator objects. Examples -------- .. code-block:: python class CapitalOrSmall(IA5String): ''' ASN.1 specification: CapitalOrSmall ::= IA5String (FROM ("A".."Z") | FROM ("a".."z")) ''' subtypeSpec = ConstraintsUnion( PermittedAlphabetConstraint('A', 'Z'), PermittedAlphabetConstraint('a', 'z') ) # this will succeed capital_or_small = CapitalAndSmall('Hello') # this will raise ValueConstraintError capital_or_small = CapitalOrSmall('hello!') c鬄|jD]&} |||dS#tj$rY#wxYwtjd|jd|d)Nzall of z failed for ""rros rr zConstraintsUnion._testValues,  圝  5#&&&-     ((+/<<< ?   s ,,Nrpr(rrr r s.%%餖      rr )sys pyasn1.typer__all__objectrrrrrrrrrr r rr r r(rrrs    K3K3K3K3K3K3K3K3餦9C9C9C9C9C.9C9C9C饃)8)8)8)8)8!3)8)8)8餢5454545454-545454餻9494949494.949494饃Q4Q4Q4Q4Q4"7Q4Q4Q4餳-----!3---養77777 2777養L4L4L4L4L41L4L4L4餪44444,4446.4.4.4.4.4-.4.4.4餬@@@@@.@@@6)#)#)#)#)#3)#)#)#餢2 2 2 2 2 ,2 2 2 2 2 rPK!1%(%( __pycache__/char.cpython-311.pycnu刐迭 辤$箬ddlZddlmZddlmZddlmZgdZejZejZGddej Z Gdd e Z Gd d e Z Gd d e Z Gdde ZGdde ZGdde ZGdde ZGdde ZGddeZGdde ZGdde ZGdde ZGd d!e ZdS)"N)error)tag)univ) NumericStringPrintableString TeletexString T61StringVideotexString IA5String GraphicString VisibleString ISO646String GeneralStringUniversalString BMPString UTF8Stringc驢eZdZdZdZdZdZd dZd dZdZ dd Z d Z d S)AbstractCharacterStringaCreates |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.SimpleAsn1Type`, its objects are immutable and duck-type :class:`bytes`. When used in octet-stream context, |ASN.1| type assumes "|encoding|" encoding. Keyword Args ------------ value: :class:`str`, :class:`bytes` or |ASN.1| object :class:`str`, alternatively :class:`bytes` representing octet-stream of serialised unicode string (note `encoding` parameter) or |ASN.1| class instance. If `value` is not given, schema object will be created. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s). Constraints verification for |ASN.1| type occurs automatically on object instantiation. encoding: :py:class:`str` Unicode codec ID to encode/decode :class:`str` the payload when |ASN.1| object is used in octet-stream context. Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer. c*t|jSN)str_valueselfs 鷓/builddir/build/BUILD/imunify360-venv-2.6.2/opt/imunify360/venv/lib/python3.11/site-packages/pyasn1/type/char.py__str__zAbstractCharacterString.__str__8s4;c蟀 |j|jS#t$r*}t jd|jd|j|d}~wwxYw)NzCan't encode string ' ' with codec )rencodeencodingUnicodeEncodeErrorrPyAsn1UnicodeEncodeError)rexcs r __bytes__z!AbstractCharacterString.__bytes__;sm ;%%燿44 4!   00 燭燷458  鴖! A%AAc( t|tr|St|tr||jSt|t t fr"|t|St|tj r,| |jSt|S#ttf$r%}tjd|d|j|d}~wwxYw)NzCan't decode string 'r) isinstancerbytesdecoder!tuplelistprettyInr OctetStringasOctetsUnicodeDecodeError LookupErrorrPyAsn1UnicodeDecodeError)rvaluer$s rr,z AbstractCharacterString.prettyInDs %%% " 楨5)) "梶抾燚222楨4=11 "梷拀5222楨4#344 "梸拁''..╰瑌===5憐攝!"0   00榯渳榼./2  鴖/C.C=CAC CD, D  DTc t|Sr)r(rpaddings rr.z AbstractCharacterString.asOctetsWs怲墈寋rc:tt|Sr)r*r(r4s r asNumbersz!AbstractCharacterString.asNumbersZs昒4慬擺!!!rc|Sr)rr2s r prettyOutz!AbstractCharacterString.prettyOutas rrc髝||j}||jur|St|Sr)r:rrr)rscoper2s r prettyPrintz#AbstractCharacterString.prettyPrintds;榯渰++  # #圠&..╰444rc*t|jSr)reversedrrs r __reversed__z$AbstractCharacterString.__reversed__ms $$$rN)T)r) __name__ __module__ __qualname____doc__rr%r,r.r7r:r=r@r9rrrrs  餌   &""""5555%%%%%rrc蟀eZdZejZejejej ej dZdZ e Z dS)rus-asciiNrArBrCrrDtagSet tagImplicitlyrTagtagClassUniversaltagFormatSimpler! getTypeIdtypeIdr9rrrrq骳%-G % + 9 9%爏':窧??FH% . . 0 0FFFrrc蟀eZdZejZejejej ej dZdZ e Z dS)rrGNrHr9rrrrrPrrc蟀eZdZejZejejej ej dZdZ e Z dS)r iso-8859-1NrHr9rrrr骳%-G % + 9 9%爏':窧??FH% . . 0 0FFFrrc驞eZdZejZeZdS)r N)rArBrCrrDrrNrOr9rrr r )#G% . . 0 0FFFrr c蟀eZdZejZejejej ej dZdZ e Z dS)r rUNrHr9rrr r rVrr c蟀eZdZejZejejej ej dZdZ e Z dS)r rGNrHr9rrr r rPrr c蟀eZdZejZejejej ej dZdZ e Z dS)r rUNrHr9rrr r rVrr c蟀eZdZejZejejej ej dZdZ e Z dS)r rGNrHr9rrr r rPrr c驞eZdZejZeZdS)rN)rArBrCr rDrrNrOr9rrrrrXrrc蟀eZdZejZejejej ej dZdZ e Z dS)rrUNrHr9rrrrrVrrc蟀eZdZejZejejej ej dZdZ e Z dS)rz utf-32-beNrHr9rrrr骳%-G % + 9 9%爏':窧??FH% . . 0 0FFFrrc蟀eZdZejZejejej ej dZdZ e Z dS)rz utf-16-beNrHr9rrrrrfrrc蟀eZdZejZejejej ej dZdZ e Z dS)r zutf-8NrHr9rrrrsc%-G % + 9 9%爏':窧??FH% . . 0 0FFFrr)syspyasn1r pyasn1.typerr__all__NoValuenoValuer-rrrrr r r r r rrrrrr9rrrqs  J J J , ,Y%Y%Y%Y%Y%榙.Y%Y%Y%饃 1 1 1 1 1+ 1 1 1 1 1 1 1 1- 1 1 1 1 1 1 1 1+ 1 1 111111 111 1 1 1 1 1, 1 1 1 1 1 1 1 1' 1 1 1 1 1 1 1 1+ 1 1 1 1 1 1 1 1+ 1 1 111111=111 1 1 1 1 1+ 1 1 1 1 1 1 1 1- 1 1 1 1 1 1 1 1' 1 1 1 1 1 1 1 1( 1 1 1 1 1rPK!xΙ!!$__pycache__/namedval.cpython-311.pycnu刐迭 辤#4ddlmZdgZGddeZdS))error NamedValuesc髳eZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZdS)raCreate named values object. The |NamedValues| object represents a collection of string names associated with numeric IDs. These objects are used for giving names to otherwise numerical values. |NamedValues| objects are immutable and duck-type Python :class:`dict` object mapping ID to name and vice-versa. Parameters ---------- *args: variable number of two-element :py:class:`tuple` name: :py:class:`str` Value label value: :py:class:`int` Numeric value Keyword Args ------------ name: :py:class:`str` Value label value: :py:class:`int` Numeric value Examples -------- .. code-block:: pycon >>> nv = NamedValues('a', 'b', ('c', 0), d=1) >>> nv >>> {'c': 0, 'd': 1, 'a': 2, 'b': 3} >>> nv[0] 'c' >>> nv['a'] 2 c驚i|_i|_g}|D]穧t|ttfr, |\}}n;#t $rt jd|wxYw||宍||jvrt jd|||jvrt jd|d|||j|<||j|<尭| D]\\}}||jvrt jd|||jvrt jd|d|||j|<||j|<宂|r^|jrt|jdzpd}|D]=}||jvrt jd|||j|<||j|<|dz }z(NamedValues.__repr__..ks#F#F#F癆燝╝#F#F#F锧 z...i)joinrlen __class____name__)rrepresentations r__repr__zNamedValues.__repr__js#F#F#F#F#FGG 垀   # #+–≧–058>#$$;OO圢 孨 # # #燸燸燸5 5r"c(t||kSNdictrothers r__eq__zNamedValues.__eq__s怐墇寊楿""r"c(t||kSr.r/r1s r__ne__zNamedValues.__ne__vr4r"c(t||kSr.r/r1s r__lt__zNamedValues.__lt__y怐墇寊楨!!r"c(t||kSr.r/r1s r__le__zNamedValues.__le__|r4r"c(t||kSr.r/r1s r__gt__zNamedValues.__gt__r9r"c(t||kSr.r/r1s r__ge__zNamedValues.__ge__r4r"c驞t|Sr.)hashrrs r__hash__zNamedValues.__hash__s怐桱扟慙擫!!!r"c骕 |j|S#t$r|j|cYSwxYwr.)r KeyErrorr rkeys r __getitem__zNamedValues.__getitem__sB %>#& & % % %<$ $ $ $ %鴖 ))c*t|jSr.)r(r rBs r__len__zNamedValues.__len__s4<   r"c&||jvp||jvSr.)r r rFs r __contains__zNamedValues.__contains__s恉攍";燾═琟&;;r"c*t|jSr.iterr rBs r__iter__zNamedValues.__iter__怐擫!!!r"c*t|jSr.)rOr rBs rvalueszNamedValues.valuess怐擭###r"c*t|jSr.rNrBs rkeyszNamedValues.keysrQr"c#驚K|jD]}||j|fVdSr.r rrs rrzNamedValues.itemss<擫 + +圖 燭** * * * * + +r"c髽|jt|t|zSr.)r)r r)r namedValuess r__add__zNamedValues.__add__s:坱寏漸燭22礥;;L;L;N;N5O5OOPPr"c&|j|i|}||zSr.)r))rrrnews rclonezNamedValues.clones"坉宯榙-爁--恈墇r"c2||jvr |j|SdSr.)r )rvalues rgetNamezNamedValues.getNames$ 怐擭 " ">%( ( # "r"c2||jvr |j|SdSr.rWrXs rgetValuezNamedValues.getValues$ 4<  <% % r"c蠖 fd|DS#t$r=tjdt|jwxYw)Nc*g|]}j|SrrW)rrrs rr!z)NamedValues.getValues..s 鴢9994怐擫&999r"zUnknown bit identifier(s): )rErrset differencer )rnamess` r getValueszNamedValues.getValuesst鴢 99995999 9   ##36皍::3H3H3V3V3VX  鴖 慉AN)r* __module__ __qualname____doc__rr,r3r6r8r;r=r?rCrHrJrLrPrSrUrr[r^rarcrirr"rrrs^''餚111餱555######"""###"""###""" %%%!!!<<<"""$$$"""+++ QQQ  )))&&&r"N)pyasn1r__all__objectrrr"rrps^ /rrrrr&rrrrrr"PK!4:II"__pycache__/tagmap.cpython-311.pycnu刐迭 辤 4ddlmZdgZGddeZdS))errorTagMapc髥eZdZdZddZdZdZdZdZe dZ e d Z e d Z d Z d Zd ZdS)raFMap *TagSet* objects to ASN.1 types Create an object mapping *TagSet* object to ASN.1 type. *TagMap* objects are immutable and duck-type read-only Python :class:`dict` objects holding *TagSet* objects as keys and ASN.1 type objects as values. Parameters ---------- presentTypes: :py:class:`dict` Map of :class:`~pyasn1.type.tag.TagSet` to ASN.1 objects considered as being unconditionally present in the *TagMap*. skipTypes: :py:class:`dict` A collection of :class:`~pyasn1.type.tag.TagSet` objects considered as absent in the *TagMap* even when *defaultType* is present. defaultType: ASN.1 type object An ASN.1 type object callee *TagMap* returns for any *TagSet* key not present in *presentTypes* (unless given key is present in *skipTypes*). Nc8|pi|_|pi|_||_dSN)_TagMap__presentTypes_TagMap__skipTypes_TagMap__defaultType)self presentTypes skipTypes defaultTypes 鷕/builddir/build/BUILD/imunify360-venv-2.6.2/opt/imunify360/venv/lib/python3.11/site-packages/pyasn1/type/tagmap.py__init__zTagMap.__init__#s)*0╞$?(c8||jvp|jduo||jvSr)rr r r tagSets r __contains__zTagMap.__contains__(s1$--R"$.Q6訟Q3Q Src髺 |j|S#t$r/|j||jvrt jd|jcYSwxYw)NzKey in negative map)rKeyErrorr r r PyAsn1Errorrs r __getitem__zTagMap.__getitem__,sk *&爒. . * * *!)4+++'(=>>>))))  *鴖 6AAc*t|jSr)iterrr s r__iter__zTagMap.__iter__7s怐'(((rc箴d|jjz}|jr|dt|jzz }|jr|dt|jzz }|j|dt|jzz }d|zS)Nz %s objectz , present %sz , skip %sz , default %sz<%s>) __class____name__rreprr r )r representations r__repr__zTagMap.__repr__:s$爐'>>   I 榥璽癉4G/H/HH H圢   C 榢璂1A,B,BB B圢   ) 榥璽癉4F/G/GG G圢&&rc|jS)zr5s^ *T T T T T 圴T T T T T rPK!馼軟## namedval.pynu刐迭# # This file is part of pyasn1 software. # # Copyright (c) 2005-2020, Ilya Etingof # License: https://pyasn1.readthedocs.io/en/latest/license.html # # ASN.1 named integers # from pyasn1 import error __all__ = ['NamedValues'] class NamedValues(object): """Create named values object. The |NamedValues| object represents a collection of string names associated with numeric IDs. These objects are used for giving names to otherwise numerical values. |NamedValues| objects are immutable and duck-type Python :class:`dict` object mapping ID to name and vice-versa. Parameters ---------- *args: variable number of two-element :py:class:`tuple` name: :py:class:`str` Value label value: :py:class:`int` Numeric value Keyword Args ------------ name: :py:class:`str` Value label value: :py:class:`int` Numeric value Examples -------- .. code-block:: pycon >>> nv = NamedValues('a', 'b', ('c', 0), d=1) >>> nv >>> {'c': 0, 'd': 1, 'a': 2, 'b': 3} >>> nv[0] 'c' >>> nv['a'] 2 """ def __init__(self, *args, **kwargs): self.__names = {} self.__numbers = {} anonymousNames = [] for namedValue in args: if isinstance(namedValue, (tuple, list)): try: name, number = namedValue except ValueError: raise error.PyAsn1Error('Not a proper attribute-value pair %r' % (namedValue,)) else: anonymousNames.append(namedValue) continue if name in self.__names: raise error.PyAsn1Error('Duplicate name %s' % (name,)) if number in self.__numbers: raise error.PyAsn1Error('Duplicate number %s=%s' % (name, number)) self.__names[name] = number self.__numbers[number] = name for name, number in kwargs.items(): if name in self.__names: raise error.PyAsn1Error('Duplicate name %s' % (name,)) if number in self.__numbers: raise error.PyAsn1Error('Duplicate number %s=%s' % (name, number)) self.__names[name] = number self.__numbers[number] = name if anonymousNames: number = self.__numbers and max(self.__numbers) + 1 or 0 for name in anonymousNames: if name in self.__names: raise error.PyAsn1Error('Duplicate name %s' % (name,)) self.__names[name] = number self.__numbers[number] = name number += 1 def __repr__(self): representation = ', '.join(['%s=%d' % x for x in self.items()]) if len(representation) > 64: representation = representation[:32] + '...' + representation[-32:] return '<%s object, enums %s>' % ( self.__class__.__name__, representation) def __eq__(self, other): return dict(self) == other def __ne__(self, other): return dict(self) != other def __lt__(self, other): return dict(self) < other def __le__(self, other): return dict(self) <= other def __gt__(self, other): return dict(self) > other def __ge__(self, other): return dict(self) >= other def __hash__(self): return hash(self.items()) # Python dict protocol (read-only) def __getitem__(self, key): try: return self.__numbers[key] except KeyError: return self.__names[key] def __len__(self): return len(self.__names) def __contains__(self, key): return key in self.__names or key in self.__numbers def __iter__(self): return iter(self.__names) def values(self): return iter(self.__numbers) def keys(self): return iter(self.__names) def items(self): for name in self.__names: yield name, self.__names[name] # support merging def __add__(self, namedValues): return self.__class__(*tuple(self.items()) + tuple(namedValues.items())) # XXX clone/subtype? def clone(self, *args, **kwargs): new = self.__class__(*args, **kwargs) return self + new # legacy protocol def getName(self, value): if value in self.__numbers: return self.__numbers[value] def getValue(self, name): if name in self.__names: return self.__names[name] def getValues(self, *names): try: return [self.__names[name] for name in names] except KeyError: raise error.PyAsn1Error( 'Unknown bit identifier(s): %s' % (set(names).difference(self.__names),) ) PK!珥"V"Vbase.pynu刐迭# # This file is part of pyasn1 software. # # Copyright (c) 2005-2020, Ilya Etingof # License: https://pyasn1.readthedocs.io/en/latest/license.html # import sys from pyasn1 import error from pyasn1.type import constraint from pyasn1.type import tag from pyasn1.type import tagmap __all__ = ['Asn1Item', 'Asn1Type', 'SimpleAsn1Type', 'ConstructedAsn1Type'] class Asn1Item(object): @classmethod def getTypeId(cls, increment=1): try: Asn1Item._typeCounter += increment except AttributeError: Asn1Item._typeCounter = increment return Asn1Item._typeCounter class Asn1Type(Asn1Item): """Base class for all classes representing ASN.1 types. In the user code, |ASN.1| class is normally used only for telling ASN.1 objects from others. Note ---- For as long as ASN.1 is concerned, a way to compare ASN.1 types is to use :meth:`isSameTypeWith` and :meth:`isSuperTypeOf` methods. """ #: Set or return a :py:class:`~pyasn1.type.tag.TagSet` object representing #: ASN.1 tag(s) associated with |ASN.1| type. tagSet = tag.TagSet() #: Default :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` #: object imposing constraints on initialization values. subtypeSpec = constraint.ConstraintsIntersection() # Disambiguation ASN.1 types identification typeId = None def __init__(self, **kwargs): readOnly = { 'tagSet': self.tagSet, 'subtypeSpec': self.subtypeSpec } readOnly.update(kwargs) self.__dict__.update(readOnly) self._readOnly = readOnly def __setattr__(self, name, value): if name[0] != '_' and name in self._readOnly: raise error.PyAsn1Error('read-only instance attribute "%s"' % name) self.__dict__[name] = value def __str__(self): return self.prettyPrint() @property def readOnly(self): return self._readOnly @property def effectiveTagSet(self): """For |ASN.1| type is equivalent to *tagSet* """ return self.tagSet # used by untagged types @property def tagMap(self): """Return a :class:`~pyasn1.type.tagmap.TagMap` object mapping ASN.1 tags to ASN.1 objects within callee object. """ return tagmap.TagMap({self.tagSet: self}) def isSameTypeWith(self, other, matchTags=True, matchConstraints=True): """Examine |ASN.1| type for equality with other ASN.1 type. ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints (:py:mod:`~pyasn1.type.constraint`) are examined when carrying out ASN.1 types comparison. Python class inheritance relationship is NOT considered. Parameters ---------- other: a pyasn1 type object Class instance representing ASN.1 type. Returns ------- : :class:`bool` :obj:`True` if *other* is |ASN.1| type, :obj:`False` otherwise. """ return (self is other or (not matchTags or self.tagSet == other.tagSet) and (not matchConstraints or self.subtypeSpec == other.subtypeSpec)) def isSuperTypeOf(self, other, matchTags=True, matchConstraints=True): """Examine |ASN.1| type for subtype relationship with other ASN.1 type. ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints (:py:mod:`~pyasn1.type.constraint`) are examined when carrying out ASN.1 types comparison. Python class inheritance relationship is NOT considered. Parameters ---------- other: a pyasn1 type object Class instance representing ASN.1 type. Returns ------- : :class:`bool` :obj:`True` if *other* is a subtype of |ASN.1| type, :obj:`False` otherwise. """ return (not matchTags or (self.tagSet.isSuperTagSetOf(other.tagSet)) and (not matchConstraints or self.subtypeSpec.isSuperTypeOf(other.subtypeSpec))) @staticmethod def isNoValue(*values): for value in values: if value is not noValue: return False return True def prettyPrint(self, scope=0): raise NotImplementedError # backward compatibility def getTagSet(self): return self.tagSet def getEffectiveTagSet(self): return self.effectiveTagSet def getTagMap(self): return self.tagMap def getSubtypeSpec(self): return self.subtypeSpec # backward compatibility def hasValue(self): return self.isValue # Backward compatibility Asn1ItemBase = Asn1Type class NoValue(object): """Create a singleton instance of NoValue class. The *NoValue* sentinel object represents an instance of ASN.1 schema object as opposed to ASN.1 value object. Only ASN.1 schema-related operations can be performed on ASN.1 schema objects. Warning ------- Any operation attempted on the *noValue* object will raise the *PyAsn1Error* exception. """ skipMethods = { '__slots__', # attributes '__getattribute__', '__getattr__', '__setattr__', '__delattr__', # class instance '__class__', '__init__', '__del__', '__new__', '__repr__', '__qualname__', '__objclass__', 'im_class', '__sizeof__', # pickle protocol '__reduce__', '__reduce_ex__', '__getnewargs__', '__getinitargs__', '__getstate__', '__setstate__', } _instance = None def __new__(cls): if cls._instance is None: def getPlug(name): def plug(self, *args, **kw): raise error.PyAsn1Error('Attempted "%s" operation on ASN.1 schema object' % name) return plug op_names = [name for typ in (str, int, list, dict) for name in dir(typ) if (name not in cls.skipMethods and name.startswith('__') and name.endswith('__') and callable(getattr(typ, name)))] for name in set(op_names): setattr(cls, name, getPlug(name)) cls._instance = object.__new__(cls) return cls._instance def __getattr__(self, attr): if attr in self.skipMethods: raise AttributeError('Attribute %s not present' % attr) raise error.PyAsn1Error('Attempted "%s" operation on ASN.1 schema object' % attr) def __repr__(self): return '<%s object>' % self.__class__.__name__ noValue = NoValue() class SimpleAsn1Type(Asn1Type): """Base class for all simple classes representing ASN.1 types. ASN.1 distinguishes types by their ability to hold other objects. Scalar types are known as *simple* in ASN.1. In the user code, |ASN.1| class is normally used only for telling ASN.1 objects from others. Note ---- For as long as ASN.1 is concerned, a way to compare ASN.1 types is to use :meth:`isSameTypeWith` and :meth:`isSuperTypeOf` methods. """ #: Default payload value defaultValue = noValue def __init__(self, value=noValue, **kwargs): Asn1Type.__init__(self, **kwargs) if value is noValue: value = self.defaultValue else: value = self.prettyIn(value) try: self.subtypeSpec(value) except error.PyAsn1Error as exValue: raise type(exValue)('%s at %s' % (exValue, self.__class__.__name__)) self._value = value def __repr__(self): representation = '%s %s object' % ( self.__class__.__name__, self.isValue and 'value' or 'schema') for attr, value in self.readOnly.items(): if value: representation += ', %s %s' % (attr, value) if self.isValue: value = self.prettyPrint() if len(value) > 32: value = value[:16] + '...' + value[-16:] representation += ', payload [%s]' % value return '<%s>' % representation def __eq__(self, other): if self is other: return True return self._value == other def __ne__(self, other): return self._value != other def __lt__(self, other): return self._value < other def __le__(self, other): return self._value <= other def __gt__(self, other): return self._value > other def __ge__(self, other): return self._value >= other def __bool__(self): return bool(self._value) def __hash__(self): return hash(self._value) @property def isValue(self): """Indicate that |ASN.1| object represents ASN.1 value. If *isValue* is :obj:`False` then this object represents just ASN.1 schema. If *isValue* is :obj:`True` then, in addition to its ASN.1 schema features, this object can also be used like a Python built-in object (e.g. :class:`int`, :class:`str`, :class:`dict` etc.). Returns ------- : :class:`bool` :obj:`False` if object represents just ASN.1 schema. :obj:`True` if object represents ASN.1 schema and can be used as a normal value. Note ---- There is an important distinction between PyASN1 schema and value objects. The PyASN1 schema objects can only participate in ASN.1 schema-related operations (e.g. defining or testing the structure of the data). Most obvious uses of ASN.1 schema is to guide serialisation codecs whilst encoding/decoding serialised ASN.1 contents. The PyASN1 value objects can **additionally** participate in many operations involving regular Python objects (e.g. arithmetic, comprehension etc). """ return self._value is not noValue def clone(self, value=noValue, **kwargs): """Create a modified version of |ASN.1| schema or value object. The `clone()` method accepts the same set arguments as |ASN.1| class takes on instantiation except that all arguments of the `clone()` method are optional. Whatever arguments are supplied, they are used to create a copy of `self` taking precedence over the ones used to instantiate `self`. Note ---- Due to the immutable nature of the |ASN.1| object, if no arguments are supplied, no new |ASN.1| object will be created and `self` will be returned instead. """ if value is noValue: if not kwargs: return self value = self._value initializers = self.readOnly.copy() initializers.update(kwargs) return self.__class__(value, **initializers) def subtype(self, value=noValue, **kwargs): """Create a specialization of |ASN.1| schema or value object. The subtype relationship between ASN.1 types has no correlation with subtype relationship between Python types. ASN.1 type is mainly identified by its tag(s) (:py:class:`~pyasn1.type.tag.TagSet`) and value range constraints (:py:class:`~pyasn1.type.constraint.ConstraintsIntersection`). These ASN.1 type properties are implemented as |ASN.1| attributes. The `subtype()` method accepts the same set arguments as |ASN.1| class takes on instantiation except that all parameters of the `subtype()` method are optional. With the exception of the arguments described below, the rest of supplied arguments they are used to create a copy of `self` taking precedence over the ones used to instantiate `self`. The following arguments to `subtype()` create a ASN.1 subtype out of |ASN.1| type: Other Parameters ---------------- implicitTag: :py:class:`~pyasn1.type.tag.Tag` Implicitly apply given ASN.1 tag object to `self`'s :py:class:`~pyasn1.type.tag.TagSet`, then use the result as new object's ASN.1 tag(s). explicitTag: :py:class:`~pyasn1.type.tag.Tag` Explicitly apply given ASN.1 tag object to `self`'s :py:class:`~pyasn1.type.tag.TagSet`, then use the result as new object's ASN.1 tag(s). subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Add ASN.1 constraints object to one of the `self`'s, then use the result as new object's ASN.1 constraints. Returns ------- : new instance of |ASN.1| schema or value object Note ---- Due to the immutable nature of the |ASN.1| object, if no arguments are supplied, no new |ASN.1| object will be created and `self` will be returned instead. """ if value is noValue: if not kwargs: return self value = self._value initializers = self.readOnly.copy() implicitTag = kwargs.pop('implicitTag', None) if implicitTag is not None: initializers['tagSet'] = self.tagSet.tagImplicitly(implicitTag) explicitTag = kwargs.pop('explicitTag', None) if explicitTag is not None: initializers['tagSet'] = self.tagSet.tagExplicitly(explicitTag) for arg, option in kwargs.items(): initializers[arg] += option return self.__class__(value, **initializers) def prettyIn(self, value): return value def prettyOut(self, value): return str(value) def prettyPrint(self, scope=0): return self.prettyOut(self._value) def prettyPrintType(self, scope=0): return '%s -> %s' % (self.tagSet, self.__class__.__name__) # Backward compatibility AbstractSimpleAsn1Item = SimpleAsn1Type # # Constructed types: # * There are five of them: Sequence, SequenceOf/SetOf, Set and Choice # * ASN1 types and values are represened by Python class instances # * Value initialization is made for defaulted components only # * Primary method of component addressing is by-position. Data model for base # type is Python sequence. Additional type-specific addressing methods # may be implemented for particular types. # * SequenceOf and SetOf types do not implement any additional methods # * Sequence, Set and Choice types also implement by-identifier addressing # * Sequence, Set and Choice types also implement by-asn1-type (tag) addressing # * Sequence and Set types may include optional and defaulted # components # * Constructed types hold a reference to component types used for value # verification and ordering. # * Component type is a scalar type for SequenceOf/SetOf types and a list # of types for Sequence/Set/Choice. # class ConstructedAsn1Type(Asn1Type): """Base class for all constructed classes representing ASN.1 types. ASN.1 distinguishes types by their ability to hold other objects. Those "nesting" types are known as *constructed* in ASN.1. In the user code, |ASN.1| class is normally used only for telling ASN.1 objects from others. Note ---- For as long as ASN.1 is concerned, a way to compare ASN.1 types is to use :meth:`isSameTypeWith` and :meth:`isSuperTypeOf` methods. """ #: If :obj:`True`, requires exact component type matching, #: otherwise subtype relation is only enforced strictConstraints = False componentType = None # backward compatibility, unused sizeSpec = constraint.ConstraintsIntersection() def __init__(self, **kwargs): readOnly = { 'componentType': self.componentType, # backward compatibility, unused 'sizeSpec': self.sizeSpec } # backward compatibility: preserve legacy sizeSpec support kwargs = self._moveSizeSpec(**kwargs) readOnly.update(kwargs) Asn1Type.__init__(self, **readOnly) def _moveSizeSpec(self, **kwargs): # backward compatibility, unused sizeSpec = kwargs.pop('sizeSpec', self.sizeSpec) if sizeSpec: subtypeSpec = kwargs.pop('subtypeSpec', self.subtypeSpec) if subtypeSpec: subtypeSpec = sizeSpec else: subtypeSpec += sizeSpec kwargs['subtypeSpec'] = subtypeSpec return kwargs def __repr__(self): representation = '%s %s object' % ( self.__class__.__name__, self.isValue and 'value' or 'schema' ) for attr, value in self.readOnly.items(): if value is not noValue: representation += ', %s=%r' % (attr, value) if self.isValue and self.components: representation += ', payload [%s]' % ', '.join( [repr(x) for x in self.components]) return '<%s>' % representation def __eq__(self, other): return self is other or self.components == other def __ne__(self, other): return self.components != other def __lt__(self, other): return self.components < other def __le__(self, other): return self.components <= other def __gt__(self, other): return self.components > other def __ge__(self, other): return self.components >= other def __bool__(self): return bool(self.components) @property def components(self): raise error.PyAsn1Error('Method not implemented') def _cloneComponentValues(self, myClone, cloneValueFlag): pass def clone(self, **kwargs): """Create a modified version of |ASN.1| schema object. The `clone()` method accepts the same set arguments as |ASN.1| class takes on instantiation except that all arguments of the `clone()` method are optional. Whatever arguments are supplied, they are used to create a copy of `self` taking precedence over the ones used to instantiate `self`. Possible values of `self` are never copied over thus `clone()` can only create a new schema object. Returns ------- : new instance of |ASN.1| type/value Note ---- Due to the mutable nature of the |ASN.1| object, even if no arguments are supplied, a new |ASN.1| object will be created and returned. """ cloneValueFlag = kwargs.pop('cloneValueFlag', False) initializers = self.readOnly.copy() initializers.update(kwargs) clone = self.__class__(**initializers) if cloneValueFlag: self._cloneComponentValues(clone, cloneValueFlag) return clone def subtype(self, **kwargs): """Create a specialization of |ASN.1| schema object. The `subtype()` method accepts the same set arguments as |ASN.1| class takes on instantiation except that all parameters of the `subtype()` method are optional. With the exception of the arguments described below, the rest of supplied arguments they are used to create a copy of `self` taking precedence over the ones used to instantiate `self`. The following arguments to `subtype()` create a ASN.1 subtype out of |ASN.1| type. Other Parameters ---------------- implicitTag: :py:class:`~pyasn1.type.tag.Tag` Implicitly apply given ASN.1 tag object to `self`'s :py:class:`~pyasn1.type.tag.TagSet`, then use the result as new object's ASN.1 tag(s). explicitTag: :py:class:`~pyasn1.type.tag.Tag` Explicitly apply given ASN.1 tag object to `self`'s :py:class:`~pyasn1.type.tag.TagSet`, then use the result as new object's ASN.1 tag(s). subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Add ASN.1 constraints object to one of the `self`'s, then use the result as new object's ASN.1 constraints. Returns ------- : new instance of |ASN.1| type/value Note ---- Due to the mutable nature of the |ASN.1| object, even if no arguments are supplied, a new |ASN.1| object will be created and returned. """ initializers = self.readOnly.copy() cloneValueFlag = kwargs.pop('cloneValueFlag', False) implicitTag = kwargs.pop('implicitTag', None) if implicitTag is not None: initializers['tagSet'] = self.tagSet.tagImplicitly(implicitTag) explicitTag = kwargs.pop('explicitTag', None) if explicitTag is not None: initializers['tagSet'] = self.tagSet.tagExplicitly(explicitTag) for arg, option in kwargs.items(): initializers[arg] += option clone = self.__class__(**initializers) if cloneValueFlag: self._cloneComponentValues(clone, cloneValueFlag) return clone def getComponentByPosition(self, idx): raise error.PyAsn1Error('Method not implemented') def setComponentByPosition(self, idx, value, verifyConstraints=True): raise error.PyAsn1Error('Method not implemented') def setComponents(self, *args, **kwargs): for idx, value in enumerate(args): self[idx] = value for k in kwargs: self[k] = kwargs[k] return self # backward compatibility def setDefaultComponents(self): pass def getComponentType(self): return self.componentType # backward compatibility, unused def verifySizeSpec(self): self.subtypeSpec(self) # Backward compatibility AbstractConstructedAsn1Item = ConstructedAsn1Type PK!c縳┺$$char.pynu刐迭# # This file is part of pyasn1 software. # # Copyright (c) 2005-2020, Ilya Etingof # License: https://pyasn1.readthedocs.io/en/latest/license.html # import sys from pyasn1 import error from pyasn1.type import tag from pyasn1.type import univ __all__ = ['NumericString', 'PrintableString', 'TeletexString', 'T61String', 'VideotexString', 'IA5String', 'GraphicString', 'VisibleString', 'ISO646String', 'GeneralString', 'UniversalString', 'BMPString', 'UTF8String'] NoValue = univ.NoValue noValue = univ.noValue class AbstractCharacterString(univ.OctetString): """Creates |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.SimpleAsn1Type`, its objects are immutable and duck-type :class:`bytes`. When used in octet-stream context, |ASN.1| type assumes "|encoding|" encoding. Keyword Args ------------ value: :class:`str`, :class:`bytes` or |ASN.1| object :class:`str`, alternatively :class:`bytes` representing octet-stream of serialised unicode string (note `encoding` parameter) or |ASN.1| class instance. If `value` is not given, schema object will be created. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s). Constraints verification for |ASN.1| type occurs automatically on object instantiation. encoding: :py:class:`str` Unicode codec ID to encode/decode :class:`str` the payload when |ASN.1| object is used in octet-stream context. Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer. """ def __str__(self): return str(self._value) def __bytes__(self): try: return self._value.encode(self.encoding) except UnicodeEncodeError as exc: raise error.PyAsn1UnicodeEncodeError( "Can't encode string '%s' with codec " "%s" % (self._value, self.encoding), exc ) def prettyIn(self, value): try: if isinstance(value, str): return value elif isinstance(value, bytes): return value.decode(self.encoding) elif isinstance(value, (tuple, list)): return self.prettyIn(bytes(value)) elif isinstance(value, univ.OctetString): return value.asOctets().decode(self.encoding) else: return str(value) except (UnicodeDecodeError, LookupError) as exc: raise error.PyAsn1UnicodeDecodeError( "Can't decode string '%s' with codec " "%s" % (value, self.encoding), exc ) def asOctets(self, padding=True): return bytes(self) def asNumbers(self, padding=True): return tuple(bytes(self)) # # See OctetString.prettyPrint() for the explanation # def prettyOut(self, value): return value def prettyPrint(self, scope=0): # first see if subclass has its own .prettyOut() value = self.prettyOut(self._value) if value is not self._value: return value return AbstractCharacterString.__str__(self) def __reversed__(self): return reversed(self._value) class NumericString(AbstractCharacterString): __doc__ = AbstractCharacterString.__doc__ #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = AbstractCharacterString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 18) ) encoding = 'us-ascii' # Optimization for faster codec lookup typeId = AbstractCharacterString.getTypeId() class PrintableString(AbstractCharacterString): __doc__ = AbstractCharacterString.__doc__ #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = AbstractCharacterString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 19) ) encoding = 'us-ascii' # Optimization for faster codec lookup typeId = AbstractCharacterString.getTypeId() class TeletexString(AbstractCharacterString): __doc__ = AbstractCharacterString.__doc__ #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = AbstractCharacterString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 20) ) encoding = 'iso-8859-1' # Optimization for faster codec lookup typeId = AbstractCharacterString.getTypeId() class T61String(TeletexString): __doc__ = TeletexString.__doc__ # Optimization for faster codec lookup typeId = AbstractCharacterString.getTypeId() class VideotexString(AbstractCharacterString): __doc__ = AbstractCharacterString.__doc__ #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = AbstractCharacterString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 21) ) encoding = 'iso-8859-1' # Optimization for faster codec lookup typeId = AbstractCharacterString.getTypeId() class IA5String(AbstractCharacterString): __doc__ = AbstractCharacterString.__doc__ #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = AbstractCharacterString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 22) ) encoding = 'us-ascii' # Optimization for faster codec lookup typeId = AbstractCharacterString.getTypeId() class GraphicString(AbstractCharacterString): __doc__ = AbstractCharacterString.__doc__ #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = AbstractCharacterString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 25) ) encoding = 'iso-8859-1' # Optimization for faster codec lookup typeId = AbstractCharacterString.getTypeId() class VisibleString(AbstractCharacterString): __doc__ = AbstractCharacterString.__doc__ #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = AbstractCharacterString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 26) ) encoding = 'us-ascii' # Optimization for faster codec lookup typeId = AbstractCharacterString.getTypeId() class ISO646String(VisibleString): __doc__ = VisibleString.__doc__ # Optimization for faster codec lookup typeId = AbstractCharacterString.getTypeId() class GeneralString(AbstractCharacterString): __doc__ = AbstractCharacterString.__doc__ #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = AbstractCharacterString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 27) ) encoding = 'iso-8859-1' # Optimization for faster codec lookup typeId = AbstractCharacterString.getTypeId() class UniversalString(AbstractCharacterString): __doc__ = AbstractCharacterString.__doc__ #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = AbstractCharacterString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 28) ) encoding = "utf-32-be" # Optimization for faster codec lookup typeId = AbstractCharacterString.getTypeId() class BMPString(AbstractCharacterString): __doc__ = AbstractCharacterString.__doc__ #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = AbstractCharacterString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 30) ) encoding = "utf-16-be" # Optimization for faster codec lookup typeId = AbstractCharacterString.getTypeId() class UTF8String(AbstractCharacterString): __doc__ = AbstractCharacterString.__doc__ #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = AbstractCharacterString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 12) ) encoding = "utf-8" # Optimization for faster codec lookup typeId = AbstractCharacterString.getTypeId() PK!鹡{c湭湭univ.pynu刐迭# # This file is part of pyasn1 software. # # Copyright (c) 2005-2020, Ilya Etingof # License: https://pyasn1.readthedocs.io/en/latest/license.html # import math import sys from pyasn1 import error from pyasn1.codec.ber import eoo from pyasn1.compat import integer from pyasn1.type import base from pyasn1.type import constraint from pyasn1.type import namedtype from pyasn1.type import namedval from pyasn1.type import tag from pyasn1.type import tagmap NoValue = base.NoValue noValue = NoValue() __all__ = ['Integer', 'Boolean', 'BitString', 'OctetString', 'Null', 'ObjectIdentifier', 'Real', 'Enumerated', 'SequenceOfAndSetOfBase', 'SequenceOf', 'SetOf', 'SequenceAndSetBase', 'Sequence', 'Set', 'Choice', 'Any', 'NoValue', 'noValue'] # "Simple" ASN.1 types (yet incomplete) class Integer(base.SimpleAsn1Type): """Create |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.SimpleAsn1Type`, its objects are immutable and duck-type Python :class:`int` objects. Keyword Args ------------ value: :class:`int`, :class:`str` or |ASN.1| object Python :class:`int` or :class:`str` literal or |ASN.1| class instance. If `value` is not given, schema object will be created. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s). Constraints verification for |ASN.1| type occurs automatically on object instantiation. namedValues: :py:class:`~pyasn1.type.namedval.NamedValues` Object representing non-default symbolic aliases for numbers Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer. Examples -------- .. code-block:: python class ErrorCode(Integer): ''' ASN.1 specification: ErrorCode ::= INTEGER { disk-full(1), no-disk(-1), disk-not-formatted(2) } error ErrorCode ::= disk-full ''' namedValues = NamedValues( ('disk-full', 1), ('no-disk', -1), ('disk-not-formatted', 2) ) error = ErrorCode('disk-full') """ #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x02) ) #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object #: imposing constraints on |ASN.1| type initialization values. subtypeSpec = constraint.ConstraintsIntersection() #: Default :py:class:`~pyasn1.type.namedval.NamedValues` object #: representing symbolic aliases for numbers namedValues = namedval.NamedValues() # Optimization for faster codec lookup typeId = base.SimpleAsn1Type.getTypeId() def __init__(self, value=noValue, **kwargs): if 'namedValues' not in kwargs: kwargs['namedValues'] = self.namedValues base.SimpleAsn1Type.__init__(self, value, **kwargs) def __and__(self, value): return self.clone(self._value & value) def __rand__(self, value): return self.clone(value & self._value) def __or__(self, value): return self.clone(self._value | value) def __ror__(self, value): return self.clone(value | self._value) def __xor__(self, value): return self.clone(self._value ^ value) def __rxor__(self, value): return self.clone(value ^ self._value) def __lshift__(self, value): return self.clone(self._value << value) def __rshift__(self, value): return self.clone(self._value >> value) def __add__(self, value): return self.clone(self._value + value) def __radd__(self, value): return self.clone(value + self._value) def __sub__(self, value): return self.clone(self._value - value) def __rsub__(self, value): return self.clone(value - self._value) def __mul__(self, value): return self.clone(self._value * value) def __rmul__(self, value): return self.clone(value * self._value) def __mod__(self, value): return self.clone(self._value % value) def __rmod__(self, value): return self.clone(value % self._value) def __pow__(self, value, modulo=None): return self.clone(pow(self._value, value, modulo)) def __rpow__(self, value): return self.clone(pow(value, self._value)) def __floordiv__(self, value): return self.clone(self._value // value) def __rfloordiv__(self, value): return self.clone(value // self._value) def __truediv__(self, value): return Real(self._value / value) def __rtruediv__(self, value): return Real(value / self._value) def __divmod__(self, value): return self.clone(divmod(self._value, value)) def __rdivmod__(self, value): return self.clone(divmod(value, self._value)) __hash__ = base.SimpleAsn1Type.__hash__ def __int__(self): return int(self._value) def __float__(self): return float(self._value) def __abs__(self): return self.clone(abs(self._value)) def __index__(self): return int(self._value) def __pos__(self): return self.clone(+self._value) def __neg__(self): return self.clone(-self._value) def __invert__(self): return self.clone(~self._value) def __round__(self, n=0): r = round(self._value, n) if n: return self.clone(r) else: return r def __floor__(self): return math.floor(self._value) def __ceil__(self): return math.ceil(self._value) def __trunc__(self): return self.clone(math.trunc(self._value)) def __lt__(self, value): return self._value < value def __le__(self, value): return self._value <= value def __eq__(self, value): return self._value == value def __ne__(self, value): return self._value != value def __gt__(self, value): return self._value > value def __ge__(self, value): return self._value >= value def prettyIn(self, value): try: return int(value) except ValueError: try: return self.namedValues[value] except KeyError as exc: raise error.PyAsn1Error( 'Can\'t coerce %r into integer: %s' % (value, exc) ) def prettyOut(self, value): try: return str(self.namedValues[value]) except KeyError: return str(value) # backward compatibility def getNamedValues(self): return self.namedValues class Boolean(Integer): """Create |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.SimpleAsn1Type`, its objects are immutable and duck-type Python :class:`int` objects. Keyword Args ------------ value: :class:`int`, :class:`str` or |ASN.1| object Python :class:`int` or :class:`str` literal or |ASN.1| class instance. If `value` is not given, schema object will be created. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s).Constraints verification for |ASN.1| type occurs automatically on object instantiation. namedValues: :py:class:`~pyasn1.type.namedval.NamedValues` Object representing non-default symbolic aliases for numbers Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer. Examples -------- .. code-block:: python class RoundResult(Boolean): ''' ASN.1 specification: RoundResult ::= BOOLEAN ok RoundResult ::= TRUE ko RoundResult ::= FALSE ''' ok = RoundResult(True) ko = RoundResult(False) """ #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x01), ) #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object #: imposing constraints on |ASN.1| type initialization values. subtypeSpec = Integer.subtypeSpec + constraint.SingleValueConstraint(0, 1) #: Default :py:class:`~pyasn1.type.namedval.NamedValues` object #: representing symbolic aliases for numbers namedValues = namedval.NamedValues(('False', 0), ('True', 1)) # Optimization for faster codec lookup typeId = Integer.getTypeId() class SizedInteger(int): bitLength = leadingZeroBits = None def setBitLength(self, bitLength): self.bitLength = bitLength self.leadingZeroBits = max(bitLength - self.bit_length(), 0) return self def __len__(self): if self.bitLength is None: self.setBitLength(self.bit_length()) return self.bitLength class BitString(base.SimpleAsn1Type): """Create |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.SimpleAsn1Type`, its objects are immutable and duck-type both Python :class:`tuple` (as a tuple of bits) and :class:`int` objects. Keyword Args ------------ value: :class:`int`, :class:`str` or |ASN.1| object Python :class:`int` or :class:`str` literal representing binary or hexadecimal number or sequence of integer bits or |ASN.1| object. If `value` is not given, schema object will be created. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s). Constraints verification for |ASN.1| type occurs automatically on object instantiation. namedValues: :py:class:`~pyasn1.type.namedval.NamedValues` Object representing non-default symbolic aliases for numbers binValue: :py:class:`str` Binary string initializer to use instead of the *value*. Example: '10110011'. hexValue: :py:class:`str` Hexadecimal string initializer to use instead of the *value*. Example: 'DEADBEEF'. Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer. Examples -------- .. code-block:: python class Rights(BitString): ''' ASN.1 specification: Rights ::= BIT STRING { user-read(0), user-write(1), group-read(2), group-write(3), other-read(4), other-write(5) } group1 Rights ::= { group-read, group-write } group2 Rights ::= '0011'B group3 Rights ::= '3'H ''' namedValues = NamedValues( ('user-read', 0), ('user-write', 1), ('group-read', 2), ('group-write', 3), ('other-read', 4), ('other-write', 5) ) group1 = Rights(('group-read', 'group-write')) group2 = Rights('0011') group3 = Rights(0x3) """ #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x03) ) #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object #: imposing constraints on |ASN.1| type initialization values. subtypeSpec = constraint.ConstraintsIntersection() #: Default :py:class:`~pyasn1.type.namedval.NamedValues` object #: representing symbolic aliases for numbers namedValues = namedval.NamedValues() # Optimization for faster codec lookup typeId = base.SimpleAsn1Type.getTypeId() defaultBinValue = defaultHexValue = noValue def __init__(self, value=noValue, **kwargs): if value is noValue: if kwargs: try: value = self.fromBinaryString(kwargs.pop('binValue'), internalFormat=True) except KeyError: pass try: value = self.fromHexString(kwargs.pop('hexValue'), internalFormat=True) except KeyError: pass if value is noValue: if self.defaultBinValue is not noValue: value = self.fromBinaryString(self.defaultBinValue, internalFormat=True) elif self.defaultHexValue is not noValue: value = self.fromHexString(self.defaultHexValue, internalFormat=True) if 'namedValues' not in kwargs: kwargs['namedValues'] = self.namedValues base.SimpleAsn1Type.__init__(self, value, **kwargs) def __str__(self): return self.asBinary() def __eq__(self, other): other = self.prettyIn(other) return self is other or self._value == other and len(self._value) == len(other) def __ne__(self, other): other = self.prettyIn(other) return self._value != other or len(self._value) != len(other) def __lt__(self, other): other = self.prettyIn(other) return len(self._value) < len(other) or len(self._value) == len(other) and self._value < other def __le__(self, other): other = self.prettyIn(other) return len(self._value) <= len(other) or len(self._value) == len(other) and self._value <= other def __gt__(self, other): other = self.prettyIn(other) return len(self._value) > len(other) or len(self._value) == len(other) and self._value > other def __ge__(self, other): other = self.prettyIn(other) return len(self._value) >= len(other) or len(self._value) == len(other) and self._value >= other # Immutable sequence object protocol def __len__(self): return len(self._value) def __getitem__(self, i): if i.__class__ is slice: return self.clone([self[x] for x in range(*i.indices(len(self)))]) else: length = len(self._value) - 1 if i > length or i < 0: raise IndexError('bit index out of range') return (self._value >> (length - i)) & 1 def __iter__(self): length = len(self._value) while length: length -= 1 yield (self._value >> length) & 1 def __reversed__(self): return reversed(tuple(self)) # arithmetic operators def __add__(self, value): value = self.prettyIn(value) return self.clone(SizedInteger(self._value << len(value) | value).setBitLength(len(self._value) + len(value))) def __radd__(self, value): value = self.prettyIn(value) return self.clone(SizedInteger(value << len(self._value) | self._value).setBitLength(len(self._value) + len(value))) def __mul__(self, value): bitString = self._value while value > 1: bitString <<= len(self._value) bitString |= self._value value -= 1 return self.clone(bitString) def __rmul__(self, value): return self * value def __lshift__(self, count): return self.clone(SizedInteger(self._value << count).setBitLength(len(self._value) + count)) def __rshift__(self, count): return self.clone(SizedInteger(self._value >> count).setBitLength(max(0, len(self._value) - count))) def __int__(self): return int(self._value) def __float__(self): return float(self._value) def asNumbers(self): """Get |ASN.1| value as a sequence of 8-bit integers. If |ASN.1| object length is not a multiple of 8, result will be left-padded with zeros. """ return tuple(self.asOctets()) def asOctets(self): """Get |ASN.1| value as a sequence of octets. If |ASN.1| object length is not a multiple of 8, result will be left-padded with zeros. """ return integer.to_bytes(self._value, length=len(self)) def asInteger(self): """Get |ASN.1| value as a single integer value. """ return self._value def asBinary(self): """Get |ASN.1| value as a text string of bits. """ binString = bin(self._value)[2:] return '0' * (len(self._value) - len(binString)) + binString @classmethod def fromHexString(cls, value, internalFormat=False, prepend=None): """Create a |ASN.1| object initialized from the hex string. Parameters ---------- value: :class:`str` Text string like 'DEADBEEF' """ try: value = SizedInteger(value, 16).setBitLength(len(value) * 4) except ValueError as exc: raise error.PyAsn1Error('%s.fromHexString() error: %s' % (cls.__name__, exc)) if prepend is not None: value = SizedInteger( (SizedInteger(prepend) << len(value)) | value ).setBitLength(len(prepend) + len(value)) if not internalFormat: value = cls(value) return value @classmethod def fromBinaryString(cls, value, internalFormat=False, prepend=None): """Create a |ASN.1| object initialized from a string of '0' and '1'. Parameters ---------- value: :class:`str` Text string like '1010111' """ try: value = SizedInteger(value or '0', 2).setBitLength(len(value)) except ValueError as exc: raise error.PyAsn1Error('%s.fromBinaryString() error: %s' % (cls.__name__, exc)) if prepend is not None: value = SizedInteger( (SizedInteger(prepend) << len(value)) | value ).setBitLength(len(prepend) + len(value)) if not internalFormat: value = cls(value) return value @classmethod def fromOctetString(cls, value, internalFormat=False, prepend=None, padding=0): """Create a |ASN.1| object initialized from a string. Parameters ---------- value: :class:`bytes` Text string like b'\\\\x01\\\\xff' """ value = SizedInteger(int.from_bytes(bytes(value), 'big') >> padding).setBitLength(len(value) * 8 - padding) if prepend is not None: value = SizedInteger( (SizedInteger(prepend) << len(value)) | value ).setBitLength(len(prepend) + len(value)) if not internalFormat: value = cls(value) return value def prettyIn(self, value): if isinstance(value, SizedInteger): return value elif isinstance(value, str): if not value: return SizedInteger(0).setBitLength(0) elif value[0] == '\'': # "'1011'B" -- ASN.1 schema representation (deprecated) if value[-2:] == '\'B': return self.fromBinaryString(value[1:-2], internalFormat=True) elif value[-2:] == '\'H': return self.fromHexString(value[1:-2], internalFormat=True) else: raise error.PyAsn1Error( 'Bad BIT STRING value notation %s' % (value,) ) elif self.namedValues and not value.isdigit(): # named bits like 'Urgent, Active' names = [x.strip() for x in value.split(',')] try: bitPositions = [self.namedValues[name] for name in names] except KeyError: raise error.PyAsn1Error('unknown bit name(s) in %r' % (names,)) rightmostPosition = max(bitPositions) number = 0 for bitPosition in bitPositions: number |= 1 << (rightmostPosition - bitPosition) return SizedInteger(number).setBitLength(rightmostPosition + 1) elif value.startswith('0x'): return self.fromHexString(value[2:], internalFormat=True) elif value.startswith('0b'): return self.fromBinaryString(value[2:], internalFormat=True) else: # assume plain binary string like '1011' return self.fromBinaryString(value, internalFormat=True) elif isinstance(value, (tuple, list)): return self.fromBinaryString(''.join([b and '1' or '0' for b in value]), internalFormat=True) elif isinstance(value, BitString): return SizedInteger(value).setBitLength(len(value)) elif isinstance(value, int): return SizedInteger(value) else: raise error.PyAsn1Error( 'Bad BitString initializer type \'%s\'' % (value,) ) class OctetString(base.SimpleAsn1Type): """Create |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.SimpleAsn1Type`, its objects are immutable and duck-type :class:`bytes`. When used in Unicode context, |ASN.1| type assumes "|encoding|" serialisation. Keyword Args ------------ value: :class:`unicode`, :class:`str`, :class:`bytes` or |ASN.1| object :class:`bytes`, alternatively :class:`str` representing character string to be serialised into octets (note `encoding` parameter) or |ASN.1| object. If `value` is not given, schema object will be created. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s). Constraints verification for |ASN.1| type occurs automatically on object instantiation. encoding: :py:class:`str` Unicode codec ID to encode/decode :class:`str` the payload when |ASN.1| object is used in text string context. binValue: :py:class:`str` Binary string initializer to use instead of the *value*. Example: '10110011'. hexValue: :py:class:`str` Hexadecimal string initializer to use instead of the *value*. Example: 'DEADBEEF'. Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer. Examples -------- .. code-block:: python class Icon(OctetString): ''' ASN.1 specification: Icon ::= OCTET STRING icon1 Icon ::= '001100010011001000110011'B icon2 Icon ::= '313233'H ''' icon1 = Icon.fromBinaryString('001100010011001000110011') icon2 = Icon.fromHexString('313233') """ #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x04) ) #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object #: imposing constraints on |ASN.1| type initialization values. subtypeSpec = constraint.ConstraintsIntersection() # Optimization for faster codec lookup typeId = base.SimpleAsn1Type.getTypeId() defaultBinValue = defaultHexValue = noValue encoding = 'iso-8859-1' def __init__(self, value=noValue, **kwargs): if kwargs: if value is noValue: try: value = self.fromBinaryString(kwargs.pop('binValue')) except KeyError: pass try: value = self.fromHexString(kwargs.pop('hexValue')) except KeyError: pass if value is noValue: if self.defaultBinValue is not noValue: value = self.fromBinaryString(self.defaultBinValue) elif self.defaultHexValue is not noValue: value = self.fromHexString(self.defaultHexValue) if 'encoding' not in kwargs: kwargs['encoding'] = self.encoding base.SimpleAsn1Type.__init__(self, value, **kwargs) def prettyIn(self, value): if isinstance(value, bytes): return value elif isinstance(value, str): try: return value.encode(self.encoding) except UnicodeEncodeError as exc: raise error.PyAsn1UnicodeEncodeError( "Can't encode string '%s' with '%s' " "codec" % (value, self.encoding), exc ) elif isinstance(value, OctetString): # a shortcut, bytes() would work the same way return value.asOctets() elif isinstance(value, base.SimpleAsn1Type): # this mostly targets Integer objects return self.prettyIn(str(value)) elif isinstance(value, (tuple, list)): return self.prettyIn(bytes(value)) else: return bytes(value) def __str__(self): try: return self._value.decode(self.encoding) except UnicodeDecodeError as exc: raise error.PyAsn1UnicodeDecodeError( "Can't decode string '%s' with '%s' codec at " "'%s'" % (self._value, self.encoding, self.__class__.__name__), exc ) def __bytes__(self): return bytes(self._value) def asOctets(self): return bytes(self._value) def asNumbers(self): return tuple(self._value) # # Normally, `.prettyPrint()` is called from `__str__()`. Historically, # OctetString.prettyPrint() used to return hexified payload # representation in cases when non-printable content is present. At the # same time `str()` used to produce either octet-stream (Py2) or # text (Py3) representations. # # Therefore `OctetString.__str__()` -> `.prettyPrint()` call chain is # reversed to preserve the original behaviour. # # Eventually we should deprecate `.prettyPrint()` / `.prettyOut()` harness # and end up with just `__str__()` producing hexified representation while # both text and octet-stream representation should only be requested via # the `.asOctets()` method. # # Note: ASN.1 OCTET STRING is never mean to contain text! # def prettyOut(self, value): return value def prettyPrint(self, scope=0): # first see if subclass has its own .prettyOut() value = self.prettyOut(self._value) if value is not self._value: return value numbers = self.asNumbers() for x in numbers: # hexify if needed if x < 32 or x > 126: return '0x' + ''.join(('%.2x' % x for x in numbers)) else: # this prevents infinite recursion return OctetString.__str__(self) @staticmethod def fromBinaryString(value): """Create a |ASN.1| object initialized from a string of '0' and '1'. Parameters ---------- value: :class:`str` Text string like '1010111' """ bitNo = 8 byte = 0 r = [] for v in value: if bitNo: bitNo -= 1 else: bitNo = 7 r.append(byte) byte = 0 if v in ('0', '1'): v = int(v) else: raise error.PyAsn1Error( 'Non-binary OCTET STRING initializer %s' % (v,) ) byte |= v << bitNo r.append(byte) return bytes(r) @staticmethod def fromHexString(value): """Create a |ASN.1| object initialized from the hex string. Parameters ---------- value: :class:`str` Text string like 'DEADBEEF' """ r = [] p = [] for v in value: if p: r.append(int(p + v, 16)) p = None else: p = v if p: r.append(int(p + '0', 16)) return bytes(r) # Immutable sequence object protocol def __len__(self): return len(self._value) def __getitem__(self, i): if i.__class__ is slice: return self.clone(self._value[i]) else: return self._value[i] def __iter__(self): return iter(self._value) def __contains__(self, value): return value in self._value def __add__(self, value): return self.clone(self._value + self.prettyIn(value)) def __radd__(self, value): return self.clone(self.prettyIn(value) + self._value) def __mul__(self, value): return self.clone(self._value * value) def __rmul__(self, value): return self * value def __int__(self): return int(self._value) def __float__(self): return float(self._value) def __reversed__(self): return reversed(self._value) class Null(OctetString): """Create |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.SimpleAsn1Type`, its objects are immutable and duck-type Python :class:`str` objects (always empty). Keyword Args ------------ value: :class:`str` or |ASN.1| object Python empty :class:`str` literal or any object that evaluates to :obj:`False` If `value` is not given, schema object will be created. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer. Examples -------- .. code-block:: python class Ack(Null): ''' ASN.1 specification: Ack ::= NULL ''' ack = Ack('') """ #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x05) ) subtypeSpec = OctetString.subtypeSpec + constraint.SingleValueConstraint(b'') # Optimization for faster codec lookup typeId = OctetString.getTypeId() def prettyIn(self, value): if value: return value return b'' class ObjectIdentifier(base.SimpleAsn1Type): """Create |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.SimpleAsn1Type`, its objects are immutable and duck-type Python :class:`tuple` objects (tuple of non-negative integers). Keyword Args ------------ value: :class:`tuple`, :class:`str` or |ASN.1| object Python sequence of :class:`int` or :class:`str` literal or |ASN.1| object. If `value` is not given, schema object will be created. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s). Constraints verification for |ASN.1| type occurs automatically on object instantiation. Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer. Examples -------- .. code-block:: python class ID(ObjectIdentifier): ''' ASN.1 specification: ID ::= OBJECT IDENTIFIER id-edims ID ::= { joint-iso-itu-t mhs-motif(6) edims(7) } id-bp ID ::= { id-edims 11 } ''' id_edims = ID('2.6.7') id_bp = id_edims + (11,) """ #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x06) ) #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object #: imposing constraints on |ASN.1| type initialization values. subtypeSpec = constraint.ConstraintsIntersection() # Optimization for faster codec lookup typeId = base.SimpleAsn1Type.getTypeId() def __add__(self, other): return self.clone(self._value + other) def __radd__(self, other): return self.clone(other + self._value) def asTuple(self): return self._value # Sequence object protocol def __len__(self): return len(self._value) def __getitem__(self, i): if i.__class__ is slice: return self.clone(self._value[i]) else: return self._value[i] def __iter__(self): return iter(self._value) def __contains__(self, value): return value in self._value def index(self, suboid): return self._value.index(suboid) def isPrefixOf(self, other): """Indicate if this |ASN.1| object is a prefix of other |ASN.1| object. Parameters ---------- other: |ASN.1| object |ASN.1| object Returns ------- : :class:`bool` :obj:`True` if this |ASN.1| object is a parent (e.g. prefix) of the other |ASN.1| object or :obj:`False` otherwise. """ l = len(self) if l <= len(other): if self._value[:l] == other[:l]: return True return False def prettyIn(self, value): if isinstance(value, ObjectIdentifier): return tuple(value) elif isinstance(value, str): if '-' in value: raise error.PyAsn1Error( # sys.exc_info in case prettyIn was called while handling an exception 'Malformed Object ID %s at %s: %s' % (value, self.__class__.__name__, sys.exc_info()[1]) ) try: return tuple([int(subOid) for subOid in value.split('.') if subOid]) except ValueError as exc: raise error.PyAsn1Error( 'Malformed Object ID %s at %s: %s' % (value, self.__class__.__name__, exc) ) try: tupleOfInts = tuple([int(subOid) for subOid in value if subOid >= 0]) except (ValueError, TypeError) as exc: raise error.PyAsn1Error( 'Malformed Object ID %s at %s: %s' % (value, self.__class__.__name__, exc) ) if len(tupleOfInts) == len(value): return tupleOfInts raise error.PyAsn1Error('Malformed Object ID %s at %s' % (value, self.__class__.__name__)) def prettyOut(self, value): return '.'.join([str(x) for x in value]) class RelativeOID(base.SimpleAsn1Type): """Create |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.SimpleAsn1Type`, its objects are immutable and duck-type Python :class:`tuple` objects (tuple of non-negative integers). Keyword Args ------------ value: :class:`tuple`, :class:`str` or |ASN.1| object Python sequence of :class:`int` or :class:`str` literal or |ASN.1| object. If `value` is not given, schema object will be created. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s). Constraints verification for |ASN.1| type occurs automatically on object instantiation. Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer. Examples -------- .. code-block:: python class RelOID(RelativeOID): ''' ASN.1 specification: id-pad-null RELATIVE-OID ::= { 0 } id-pad-once RELATIVE-OID ::= { 5 6 } id-pad-twice RELATIVE-OID ::= { 5 6 7 } ''' id_pad_null = RelOID('0') id_pad_once = RelOID('5.6') id_pad_twice = id_pad_once + (7,) """ #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x0d) ) #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object #: imposing constraints on |ASN.1| type initialization values. subtypeSpec = constraint.ConstraintsIntersection() # Optimization for faster codec lookup typeId = base.SimpleAsn1Type.getTypeId() def __add__(self, other): return self.clone(self._value + other) def __radd__(self, other): return self.clone(other + self._value) def asTuple(self): return self._value # Sequence object protocol def __len__(self): return len(self._value) def __getitem__(self, i): if i.__class__ is slice: return self.clone(self._value[i]) else: return self._value[i] def __iter__(self): return iter(self._value) def __contains__(self, value): return value in self._value def index(self, suboid): return self._value.index(suboid) def isPrefixOf(self, other): """Indicate if this |ASN.1| object is a prefix of other |ASN.1| object. Parameters ---------- other: |ASN.1| object |ASN.1| object Returns ------- : :class:`bool` :obj:`True` if this |ASN.1| object is a parent (e.g. prefix) of the other |ASN.1| object or :obj:`False` otherwise. """ l = len(self) if l <= len(other): if self._value[:l] == other[:l]: return True return False def prettyIn(self, value): if isinstance(value, RelativeOID): return tuple(value) elif isinstance(value, str): if '-' in value: raise error.PyAsn1Error( # sys.exc_info in case prettyIn was called while handling an exception 'Malformed RELATIVE-OID %s at %s: %s' % (value, self.__class__.__name__, sys.exc_info()[1]) ) try: return tuple([int(subOid) for subOid in value.split('.') if subOid]) except ValueError as exc: raise error.PyAsn1Error( 'Malformed RELATIVE-OID %s at %s: %s' % (value, self.__class__.__name__, exc) ) try: tupleOfInts = tuple([int(subOid) for subOid in value if subOid >= 0]) except (ValueError, TypeError) as exc: raise error.PyAsn1Error( 'Malformed RELATIVE-OID %s at %s: %s' % (value, self.__class__.__name__, exc) ) if len(tupleOfInts) == len(value): return tupleOfInts raise error.PyAsn1Error('Malformed RELATIVE-OID %s at %s' % (value, self.__class__.__name__)) def prettyOut(self, value): return '.'.join([str(x) for x in value]) class Real(base.SimpleAsn1Type): """Create |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.SimpleAsn1Type`, its objects are immutable and duck-type Python :class:`float` objects. Additionally, |ASN.1| objects behave like a :class:`tuple` in which case its elements are mantissa, base and exponent. Keyword Args ------------ value: :class:`tuple`, :class:`float` or |ASN.1| object Python sequence of :class:`int` (representing mantissa, base and exponent) or :class:`float` instance or |ASN.1| object. If `value` is not given, schema object will be created. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s). Constraints verification for |ASN.1| type occurs automatically on object instantiation. Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer. Examples -------- .. code-block:: python class Pi(Real): ''' ASN.1 specification: Pi ::= REAL pi Pi ::= { mantissa 314159, base 10, exponent -5 } ''' pi = Pi((314159, 10, -5)) """ binEncBase = None # binEncBase = 16 is recommended for large numbers try: _plusInf = float('inf') _minusInf = float('-inf') _inf = _plusInf, _minusInf except ValueError: # Infinity support is platform and Python dependent _plusInf = _minusInf = None _inf = () #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x09) ) #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object #: imposing constraints on |ASN.1| type initialization values. subtypeSpec = constraint.ConstraintsIntersection() # Optimization for faster codec lookup typeId = base.SimpleAsn1Type.getTypeId() @staticmethod def __normalizeBase10(value): m, b, e = value while m and m % 10 == 0: m /= 10 e += 1 return m, b, e def prettyIn(self, value): if isinstance(value, tuple) and len(value) == 3: if (not isinstance(value[0], (int, float)) or not isinstance(value[1], int) or not isinstance(value[2], int)): raise error.PyAsn1Error('Lame Real value syntax: %s' % (value,)) if (isinstance(value[0], float) and self._inf and value[0] in self._inf): return value[0] if value[1] not in (2, 10): raise error.PyAsn1Error( 'Prohibited base for Real value: %s' % (value[1],) ) if value[1] == 10: value = self.__normalizeBase10(value) return value elif isinstance(value, int): return self.__normalizeBase10((value, 10, 0)) elif isinstance(value, float) or isinstance(value, str): if isinstance(value, str): try: value = float(value) except ValueError: raise error.PyAsn1Error( 'Bad real value syntax: %s' % (value,) ) if self._inf and value in self._inf: return value else: e = 0 while int(value) != value: value *= 10 e -= 1 return self.__normalizeBase10((int(value), 10, e)) elif isinstance(value, Real): return tuple(value) raise error.PyAsn1Error( 'Bad real value syntax: %s' % (value,) ) def prettyPrint(self, scope=0): try: return self.prettyOut(float(self)) except OverflowError: return '' @property def isPlusInf(self): """Indicate PLUS-INFINITY object value Returns ------- : :class:`bool` :obj:`True` if calling object represents plus infinity or :obj:`False` otherwise. """ return self._value == self._plusInf @property def isMinusInf(self): """Indicate MINUS-INFINITY object value Returns ------- : :class:`bool` :obj:`True` if calling object represents minus infinity or :obj:`False` otherwise. """ return self._value == self._minusInf @property def isInf(self): return self._value in self._inf def __add__(self, value): return self.clone(float(self) + value) def __radd__(self, value): return self + value def __mul__(self, value): return self.clone(float(self) * value) def __rmul__(self, value): return self * value def __sub__(self, value): return self.clone(float(self) - value) def __rsub__(self, value): return self.clone(value - float(self)) def __mod__(self, value): return self.clone(float(self) % value) def __rmod__(self, value): return self.clone(value % float(self)) def __pow__(self, value, modulo=None): return self.clone(pow(float(self), value, modulo)) def __rpow__(self, value): return self.clone(pow(value, float(self))) def __truediv__(self, value): return self.clone(float(self) / value) def __rtruediv__(self, value): return self.clone(value / float(self)) def __divmod__(self, value): return self.clone(float(self) // value) def __rdivmod__(self, value): return self.clone(value // float(self)) def __int__(self): return int(float(self)) def __float__(self): if self._value in self._inf: return self._value else: return float( self._value[0] * pow(self._value[1], self._value[2]) ) def __abs__(self): return self.clone(abs(float(self))) def __pos__(self): return self.clone(+float(self)) def __neg__(self): return self.clone(-float(self)) def __round__(self, n=0): r = round(float(self), n) if n: return self.clone(r) else: return r def __floor__(self): return self.clone(math.floor(float(self))) def __ceil__(self): return self.clone(math.ceil(float(self))) def __trunc__(self): return self.clone(math.trunc(float(self))) def __lt__(self, value): return float(self) < value def __le__(self, value): return float(self) <= value def __eq__(self, value): return float(self) == value def __ne__(self, value): return float(self) != value def __gt__(self, value): return float(self) > value def __ge__(self, value): return float(self) >= value def __bool__(self): return bool(float(self)) __hash__ = base.SimpleAsn1Type.__hash__ def __getitem__(self, idx): if self._value in self._inf: raise error.PyAsn1Error('Invalid infinite value operation') else: return self._value[idx] # compatibility stubs def isPlusInfinity(self): return self.isPlusInf def isMinusInfinity(self): return self.isMinusInf def isInfinity(self): return self.isInf class Enumerated(Integer): """Create |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.SimpleAsn1Type`, its objects are immutable and duck-type Python :class:`int` objects. Keyword Args ------------ value: :class:`int`, :class:`str` or |ASN.1| object Python :class:`int` or :class:`str` literal or |ASN.1| object. If `value` is not given, schema object will be created. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s). Constraints verification for |ASN.1| type occurs automatically on object instantiation. namedValues: :py:class:`~pyasn1.type.namedval.NamedValues` Object representing non-default symbolic aliases for numbers Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer. Examples -------- .. code-block:: python class RadioButton(Enumerated): ''' ASN.1 specification: RadioButton ::= ENUMERATED { button1(0), button2(1), button3(2) } selected-by-default RadioButton ::= button1 ''' namedValues = NamedValues( ('button1', 0), ('button2', 1), ('button3', 2) ) selected_by_default = RadioButton('button1') """ #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x0A) ) #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object #: imposing constraints on |ASN.1| type initialization values. subtypeSpec = constraint.ConstraintsIntersection() # Optimization for faster codec lookup typeId = Integer.getTypeId() #: Default :py:class:`~pyasn1.type.namedval.NamedValues` object #: representing symbolic aliases for numbers namedValues = namedval.NamedValues() # "Structured" ASN.1 types class SequenceOfAndSetOfBase(base.ConstructedAsn1Type): """Create |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.ConstructedAsn1Type`, its objects are mutable and duck-type Python :class:`list` objects. Keyword Args ------------ componentType : :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A pyasn1 object representing ASN.1 type allowed within |ASN.1| type tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s). Constraints verification for |ASN.1| type can only occur on explicit `.isInconsistent` call. Examples -------- .. code-block:: python class LotteryDraw(SequenceOf): # SetOf is similar ''' ASN.1 specification: LotteryDraw ::= SEQUENCE OF INTEGER ''' componentType = Integer() lotteryDraw = LotteryDraw() lotteryDraw.extend([123, 456, 789]) """ def __init__(self, *args, **kwargs): # support positional params for backward compatibility if args: for key, value in zip(('componentType', 'tagSet', 'subtypeSpec'), args): if key in kwargs: raise error.PyAsn1Error('Conflicting positional and keyword params!') kwargs['componentType'] = value self._componentValues = noValue base.ConstructedAsn1Type.__init__(self, **kwargs) # Python list protocol def __getitem__(self, idx): try: return self.getComponentByPosition(idx) except error.PyAsn1Error as exc: raise IndexError(exc) def __setitem__(self, idx, value): try: self.setComponentByPosition(idx, value) except error.PyAsn1Error as exc: raise IndexError(exc) def append(self, value): if self._componentValues is noValue: pos = 0 else: pos = len(self._componentValues) self[pos] = value def count(self, value): return list(self._componentValues.values()).count(value) def extend(self, values): for value in values: self.append(value) if self._componentValues is noValue: self._componentValues = {} def index(self, value, start=0, stop=None): if stop is None: stop = len(self) indices, values = zip(*self._componentValues.items()) # TODO: remove when Py2.5 support is gone values = list(values) try: return indices[values.index(value, start, stop)] except error.PyAsn1Error as exc: raise ValueError(exc) def reverse(self): self._componentValues.reverse() def sort(self, key=None, reverse=False): self._componentValues = dict( enumerate(sorted(self._componentValues.values(), key=key, reverse=reverse))) def __len__(self): if self._componentValues is noValue or not self._componentValues: return 0 return max(self._componentValues) + 1 def __iter__(self): for idx in range(0, len(self)): yield self.getComponentByPosition(idx) def _cloneComponentValues(self, myClone, cloneValueFlag): for idx, componentValue in self._componentValues.items(): if componentValue is not noValue: if isinstance(componentValue, base.ConstructedAsn1Type): myClone.setComponentByPosition( idx, componentValue.clone(cloneValueFlag=cloneValueFlag) ) else: myClone.setComponentByPosition(idx, componentValue.clone()) def getComponentByPosition(self, idx, default=noValue, instantiate=True): """Return |ASN.1| type component value by position. Equivalent to Python sequence subscription operation (e.g. `[]`). Parameters ---------- idx : :class:`int` Component index (zero-based). Must either refer to an existing component or to N+1 component (if *componentType* is set). In the latter case a new component type gets instantiated and appended to the |ASN.1| sequence. Keyword Args ------------ default: :class:`object` If set and requested component is a schema object, return the `default` object instead of the requested component. instantiate: :class:`bool` If :obj:`True` (default), inner component will be automatically instantiated. If :obj:`False` either existing component or the :class:`NoValue` object will be returned. Returns ------- : :py:class:`~pyasn1.type.base.PyAsn1Item` Instantiate |ASN.1| component type or return existing component value Examples -------- .. code-block:: python # can also be SetOf class MySequenceOf(SequenceOf): componentType = OctetString() s = MySequenceOf() # returns component #0 with `.isValue` property False s.getComponentByPosition(0) # returns None s.getComponentByPosition(0, default=None) s.clear() # returns noValue s.getComponentByPosition(0, instantiate=False) # sets component #0 to OctetString() ASN.1 schema # object and returns it s.getComponentByPosition(0, instantiate=True) # sets component #0 to ASN.1 value object s.setComponentByPosition(0, 'ABCD') # returns OctetString('ABCD') value object s.getComponentByPosition(0, instantiate=False) s.clear() # returns noValue s.getComponentByPosition(0, instantiate=False) """ if isinstance(idx, slice): indices = tuple(range(len(self))) return [self.getComponentByPosition(subidx, default, instantiate) for subidx in indices[idx]] if idx < 0: idx = len(self) + idx if idx < 0: raise error.PyAsn1Error( 'SequenceOf/SetOf index is out of range') try: componentValue = self._componentValues[idx] except (KeyError, error.PyAsn1Error): if not instantiate: return default self.setComponentByPosition(idx) componentValue = self._componentValues[idx] if default is noValue or componentValue.isValue: return componentValue else: return default def setComponentByPosition(self, idx, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True): """Assign |ASN.1| type component by position. Equivalent to Python sequence item assignment operation (e.g. `[]`) or list.append() (when idx == len(self)). Parameters ---------- idx: :class:`int` Component index (zero-based). Must either refer to existing component or to N+1 component. In the latter case a new component type gets instantiated (if *componentType* is set, or given ASN.1 object is taken otherwise) and appended to the |ASN.1| sequence. Keyword Args ------------ value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentType* is set) or ASN.1 value object to assign to |ASN.1| component. If `value` is not given, schema object will be set as a component. verifyConstraints: :class:`bool` If :obj:`False`, skip constraints validation matchTags: :class:`bool` If :obj:`False`, skip component tags matching matchConstraints: :class:`bool` If :obj:`False`, skip component constraints matching Returns ------- self Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer IndexError When idx > len(self) """ if isinstance(idx, slice): indices = tuple(range(len(self))) startIdx = indices and indices[idx][0] or 0 for subIdx, subValue in enumerate(value): self.setComponentByPosition( startIdx + subIdx, subValue, verifyConstraints, matchTags, matchConstraints) return self if idx < 0: idx = len(self) + idx if idx < 0: raise error.PyAsn1Error( 'SequenceOf/SetOf index is out of range') componentType = self.componentType if self._componentValues is noValue: componentValues = {} else: componentValues = self._componentValues currentValue = componentValues.get(idx, noValue) if value is noValue: if componentType is not None: value = componentType.clone() elif currentValue is noValue: raise error.PyAsn1Error('Component type not defined') elif not isinstance(value, base.Asn1Item): if (componentType is not None and isinstance(componentType, base.SimpleAsn1Type)): value = componentType.clone(value=value) elif (currentValue is not noValue and isinstance(currentValue, base.SimpleAsn1Type)): value = currentValue.clone(value=value) else: raise error.PyAsn1Error( 'Non-ASN.1 value %r and undefined component' ' type at %r' % (value, self)) elif componentType is not None and (matchTags or matchConstraints): subtypeChecker = ( self.strictConstraints and componentType.isSameTypeWith or componentType.isSuperTypeOf) if not subtypeChecker(value, verifyConstraints and matchTags, verifyConstraints and matchConstraints): # TODO: we should wrap componentType with UnnamedType to carry # additional properties associated with componentType if componentType.typeId != Any.typeId: raise error.PyAsn1Error( 'Component value is tag-incompatible: %r vs ' '%r' % (value, componentType)) componentValues[idx] = value self._componentValues = componentValues return self @property def componentTagMap(self): if self.componentType is not None: return self.componentType.tagMap @property def components(self): return [self._componentValues[idx] for idx in sorted(self._componentValues)] def clear(self): """Remove all components and become an empty |ASN.1| value object. Has the same effect on |ASN.1| object as it does on :class:`list` built-in. """ self._componentValues = {} return self def reset(self): """Remove all components and become a |ASN.1| schema object. See :meth:`isValue` property for more information on the distinction between value and schema objects. """ self._componentValues = noValue return self def prettyPrint(self, scope=0): scope += 1 representation = self.__class__.__name__ + ':\n' if not self.isValue: return representation for idx, componentValue in enumerate(self): representation += ' ' * scope if (componentValue is noValue and self.componentType is not None): representation += '' else: representation += componentValue.prettyPrint(scope) return representation def prettyPrintType(self, scope=0): scope += 1 representation = '%s -> %s {\n' % (self.tagSet, self.__class__.__name__) if self.componentType is not None: representation += ' ' * scope representation += self.componentType.prettyPrintType(scope) return representation + '\n' + ' ' * (scope - 1) + '}' @property def isValue(self): """Indicate that |ASN.1| object represents ASN.1 value. If *isValue* is :obj:`False` then this object represents just ASN.1 schema. If *isValue* is :obj:`True` then, in addition to its ASN.1 schema features, this object can also be used like a Python built-in object (e.g. :class:`int`, :class:`str`, :class:`dict` etc.). Returns ------- : :class:`bool` :obj:`False` if object represents just ASN.1 schema. :obj:`True` if object represents ASN.1 schema and can be used as a normal value. Note ---- There is an important distinction between PyASN1 schema and value objects. The PyASN1 schema objects can only participate in ASN.1 schema-related operations (e.g. defining or testing the structure of the data). Most obvious uses of ASN.1 schema is to guide serialisation codecs whilst encoding/decoding serialised ASN.1 contents. The PyASN1 value objects can **additionally** participate in many operations involving regular Python objects (e.g. arithmetic, comprehension etc). """ if self._componentValues is noValue: return False if len(self._componentValues) != len(self): return False for componentValue in self._componentValues.values(): if componentValue is noValue or not componentValue.isValue: return False return True @property def isInconsistent(self): """Run necessary checks to ensure |ASN.1| object consistency. Default action is to verify |ASN.1| object against constraints imposed by `subtypeSpec`. Raises ------ :py:class:`~pyasn1.error.PyAsn1tError` on any inconsistencies found """ if self.componentType is noValue or not self.subtypeSpec: return False if self._componentValues is noValue: return True mapping = {} for idx, value in self._componentValues.items(): # Absent fields are not in the mapping if value is noValue: continue mapping[idx] = value try: # Represent SequenceOf/SetOf as a bare dict to constraints chain self.subtypeSpec(mapping) except error.PyAsn1Error as exc: return exc return False class SequenceOf(SequenceOfAndSetOfBase): __doc__ = SequenceOfAndSetOfBase.__doc__ #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x10) ) #: Default :py:class:`~pyasn1.type.base.PyAsn1Item` derivative #: object representing ASN.1 type allowed within |ASN.1| type componentType = None #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object #: imposing constraints on |ASN.1| type initialization values. subtypeSpec = constraint.ConstraintsIntersection() # Disambiguation ASN.1 types identification typeId = SequenceOfAndSetOfBase.getTypeId() class SetOf(SequenceOfAndSetOfBase): __doc__ = SequenceOfAndSetOfBase.__doc__ #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x11) ) #: Default :py:class:`~pyasn1.type.base.PyAsn1Item` derivative #: object representing ASN.1 type allowed within |ASN.1| type componentType = None #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object #: imposing constraints on |ASN.1| type initialization values. subtypeSpec = constraint.ConstraintsIntersection() # Disambiguation ASN.1 types identification typeId = SequenceOfAndSetOfBase.getTypeId() class SequenceAndSetBase(base.ConstructedAsn1Type): """Create |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.ConstructedAsn1Type`, its objects are mutable and duck-type Python :class:`dict` objects. Keyword Args ------------ componentType: :py:class:`~pyasn1.type.namedtype.NamedType` Object holding named ASN.1 types allowed within this collection tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s). Constraints verification for |ASN.1| type can only occur on explicit `.isInconsistent` call. Examples -------- .. code-block:: python class Description(Sequence): # Set is similar ''' ASN.1 specification: Description ::= SEQUENCE { surname IA5String, first-name IA5String OPTIONAL, age INTEGER DEFAULT 40 } ''' componentType = NamedTypes( NamedType('surname', IA5String()), OptionalNamedType('first-name', IA5String()), DefaultedNamedType('age', Integer(40)) ) descr = Description() descr['surname'] = 'Smith' descr['first-name'] = 'John' """ #: Default :py:class:`~pyasn1.type.namedtype.NamedTypes` #: object representing named ASN.1 types allowed within |ASN.1| type componentType = namedtype.NamedTypes() class DynamicNames(object): """Fields names/positions mapping for component-less objects""" def __init__(self): self._keyToIdxMap = {} self._idxToKeyMap = {} def __len__(self): return len(self._keyToIdxMap) def __contains__(self, item): return item in self._keyToIdxMap or item in self._idxToKeyMap def __iter__(self): return (self._idxToKeyMap[idx] for idx in range(len(self._idxToKeyMap))) def __getitem__(self, item): try: return self._keyToIdxMap[item] except KeyError: return self._idxToKeyMap[item] def getNameByPosition(self, idx): try: return self._idxToKeyMap[idx] except KeyError: raise error.PyAsn1Error('Type position out of range') def getPositionByName(self, name): try: return self._keyToIdxMap[name] except KeyError: raise error.PyAsn1Error('Name %s not found' % (name,)) def addField(self, idx): self._keyToIdxMap['field-%d' % idx] = idx self._idxToKeyMap[idx] = 'field-%d' % idx def __init__(self, **kwargs): base.ConstructedAsn1Type.__init__(self, **kwargs) self._componentTypeLen = len(self.componentType) if self._componentTypeLen: self._componentValues = [] else: self._componentValues = noValue self._dynamicNames = self._componentTypeLen or self.DynamicNames() def __getitem__(self, idx): if isinstance(idx, str): try: return self.getComponentByName(idx) except error.PyAsn1Error as exc: # duck-typing dict raise KeyError(exc) else: try: return self.getComponentByPosition(idx) except error.PyAsn1Error as exc: # duck-typing list raise IndexError(exc) def __setitem__(self, idx, value): if isinstance(idx, str): try: self.setComponentByName(idx, value) except error.PyAsn1Error as exc: # duck-typing dict raise KeyError(exc) else: try: self.setComponentByPosition(idx, value) except error.PyAsn1Error as exc: # duck-typing list raise IndexError(exc) def __contains__(self, key): if self._componentTypeLen: return key in self.componentType else: return key in self._dynamicNames def __len__(self): return len(self._componentValues) def __iter__(self): return iter(self.componentType or self._dynamicNames) # Python dict protocol def values(self): for idx in range(self._componentTypeLen or len(self._dynamicNames)): yield self[idx] def keys(self): return iter(self) def items(self): for idx in range(self._componentTypeLen or len(self._dynamicNames)): if self._componentTypeLen: yield self.componentType[idx].name, self[idx] else: yield self._dynamicNames[idx], self[idx] def update(self, *iterValue, **mappingValue): for k, v in iterValue: self[k] = v for k in mappingValue: self[k] = mappingValue[k] def clear(self): """Remove all components and become an empty |ASN.1| value object. Has the same effect on |ASN.1| object as it does on :class:`dict` built-in. """ self._componentValues = [] self._dynamicNames = self.DynamicNames() return self def reset(self): """Remove all components and become a |ASN.1| schema object. See :meth:`isValue` property for more information on the distinction between value and schema objects. """ self._componentValues = noValue self._dynamicNames = self.DynamicNames() return self @property def components(self): return self._componentValues def _cloneComponentValues(self, myClone, cloneValueFlag): if self._componentValues is noValue: return for idx, componentValue in enumerate(self._componentValues): if componentValue is not noValue: if isinstance(componentValue, base.ConstructedAsn1Type): myClone.setComponentByPosition( idx, componentValue.clone(cloneValueFlag=cloneValueFlag) ) else: myClone.setComponentByPosition(idx, componentValue.clone()) def getComponentByName(self, name, default=noValue, instantiate=True): """Returns |ASN.1| type component by name. Equivalent to Python :class:`dict` subscription operation (e.g. `[]`). Parameters ---------- name: :class:`str` |ASN.1| type component name Keyword Args ------------ default: :class:`object` If set and requested component is a schema object, return the `default` object instead of the requested component. instantiate: :class:`bool` If :obj:`True` (default), inner component will be automatically instantiated. If :obj:`False` either existing component or the :class:`NoValue` object will be returned. Returns ------- : :py:class:`~pyasn1.type.base.PyAsn1Item` Instantiate |ASN.1| component type or return existing component value """ if self._componentTypeLen: idx = self.componentType.getPositionByName(name) else: try: idx = self._dynamicNames.getPositionByName(name) except KeyError: raise error.PyAsn1Error('Name %s not found' % (name,)) return self.getComponentByPosition(idx, default=default, instantiate=instantiate) def setComponentByName(self, name, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True): """Assign |ASN.1| type component by name. Equivalent to Python :class:`dict` item assignment operation (e.g. `[]`). Parameters ---------- name: :class:`str` |ASN.1| type component name Keyword Args ------------ value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentType* is set) or ASN.1 value object to assign to |ASN.1| component. If `value` is not given, schema object will be set as a component. verifyConstraints: :class:`bool` If :obj:`False`, skip constraints validation matchTags: :class:`bool` If :obj:`False`, skip component tags matching matchConstraints: :class:`bool` If :obj:`False`, skip component constraints matching Returns ------- self """ if self._componentTypeLen: idx = self.componentType.getPositionByName(name) else: try: idx = self._dynamicNames.getPositionByName(name) except KeyError: raise error.PyAsn1Error('Name %s not found' % (name,)) return self.setComponentByPosition( idx, value, verifyConstraints, matchTags, matchConstraints ) def getComponentByPosition(self, idx, default=noValue, instantiate=True): """Returns |ASN.1| type component by index. Equivalent to Python sequence subscription operation (e.g. `[]`). Parameters ---------- idx: :class:`int` Component index (zero-based). Must either refer to an existing component or (if *componentType* is set) new ASN.1 schema object gets instantiated. Keyword Args ------------ default: :class:`object` If set and requested component is a schema object, return the `default` object instead of the requested component. instantiate: :class:`bool` If :obj:`True` (default), inner component will be automatically instantiated. If :obj:`False` either existing component or the :class:`NoValue` object will be returned. Returns ------- : :py:class:`~pyasn1.type.base.PyAsn1Item` a PyASN1 object Examples -------- .. code-block:: python # can also be Set class MySequence(Sequence): componentType = NamedTypes( NamedType('id', OctetString()) ) s = MySequence() # returns component #0 with `.isValue` property False s.getComponentByPosition(0) # returns None s.getComponentByPosition(0, default=None) s.clear() # returns noValue s.getComponentByPosition(0, instantiate=False) # sets component #0 to OctetString() ASN.1 schema # object and returns it s.getComponentByPosition(0, instantiate=True) # sets component #0 to ASN.1 value object s.setComponentByPosition(0, 'ABCD') # returns OctetString('ABCD') value object s.getComponentByPosition(0, instantiate=False) s.clear() # returns noValue s.getComponentByPosition(0, instantiate=False) """ try: if self._componentValues is noValue: componentValue = noValue else: componentValue = self._componentValues[idx] except IndexError: componentValue = noValue if not instantiate: if componentValue is noValue or not componentValue.isValue: return default else: return componentValue if componentValue is noValue: self.setComponentByPosition(idx) componentValue = self._componentValues[idx] if default is noValue or componentValue.isValue: return componentValue else: return default def setComponentByPosition(self, idx, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True): """Assign |ASN.1| type component by position. Equivalent to Python sequence item assignment operation (e.g. `[]`). Parameters ---------- idx : :class:`int` Component index (zero-based). Must either refer to existing component (if *componentType* is set) or to N+1 component otherwise. In the latter case a new component of given ASN.1 type gets instantiated and appended to |ASN.1| sequence. Keyword Args ------------ value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentType* is set) or ASN.1 value object to assign to |ASN.1| component. If `value` is not given, schema object will be set as a component. verifyConstraints : :class:`bool` If :obj:`False`, skip constraints validation matchTags: :class:`bool` If :obj:`False`, skip component tags matching matchConstraints: :class:`bool` If :obj:`False`, skip component constraints matching Returns ------- self """ componentType = self.componentType componentTypeLen = self._componentTypeLen if self._componentValues is noValue: componentValues = [] else: componentValues = self._componentValues try: currentValue = componentValues[idx] except IndexError: currentValue = noValue if componentTypeLen: if componentTypeLen < idx: raise error.PyAsn1Error('component index out of range') componentValues = [noValue] * componentTypeLen if value is noValue: if componentTypeLen: value = componentType.getTypeByPosition(idx) if isinstance(value, base.ConstructedAsn1Type): value = value.clone(cloneValueFlag=componentType[idx].isDefaulted) elif currentValue is noValue: raise error.PyAsn1Error('Component type not defined') elif not isinstance(value, base.Asn1Item): if componentTypeLen: subComponentType = componentType.getTypeByPosition(idx) if isinstance(subComponentType, base.SimpleAsn1Type): value = subComponentType.clone(value=value) else: raise error.PyAsn1Error('%s can cast only scalar values' % componentType.__class__.__name__) elif currentValue is not noValue and isinstance(currentValue, base.SimpleAsn1Type): value = currentValue.clone(value=value) else: raise error.PyAsn1Error('%s undefined component type' % componentType.__class__.__name__) elif ((verifyConstraints or matchTags or matchConstraints) and componentTypeLen): subComponentType = componentType.getTypeByPosition(idx) if subComponentType is not noValue: subtypeChecker = (self.strictConstraints and subComponentType.isSameTypeWith or subComponentType.isSuperTypeOf) if not subtypeChecker(value, verifyConstraints and matchTags, verifyConstraints and matchConstraints): if not componentType[idx].openType: raise error.PyAsn1Error('Component value is tag-incompatible: %r vs %r' % (value, componentType)) if componentTypeLen or idx in self._dynamicNames: componentValues[idx] = value elif len(componentValues) == idx: componentValues.append(value) self._dynamicNames.addField(idx) else: raise error.PyAsn1Error('Component index out of range') self._componentValues = componentValues return self @property def isValue(self): """Indicate that |ASN.1| object represents ASN.1 value. If *isValue* is :obj:`False` then this object represents just ASN.1 schema. If *isValue* is :obj:`True` then, in addition to its ASN.1 schema features, this object can also be used like a Python built-in object (e.g. :class:`int`, :class:`str`, :class:`dict` etc.). Returns ------- : :class:`bool` :obj:`False` if object represents just ASN.1 schema. :obj:`True` if object represents ASN.1 schema and can be used as a normal value. Note ---- There is an important distinction between PyASN1 schema and value objects. The PyASN1 schema objects can only participate in ASN.1 schema-related operations (e.g. defining or testing the structure of the data). Most obvious uses of ASN.1 schema is to guide serialisation codecs whilst encoding/decoding serialised ASN.1 contents. The PyASN1 value objects can **additionally** participate in many operations involving regular Python objects (e.g. arithmetic, comprehension etc). It is sufficient for |ASN.1| objects to have all non-optional and non-defaulted components being value objects to be considered as a value objects as a whole. In other words, even having one or more optional components not turned into value objects, |ASN.1| object is still considered as a value object. Defaulted components are normally value objects by default. """ if self._componentValues is noValue: return False componentType = self.componentType if componentType: for idx, subComponentType in enumerate(componentType.namedTypes): if subComponentType.isDefaulted or subComponentType.isOptional: continue if not self._componentValues: return False componentValue = self._componentValues[idx] if componentValue is noValue or not componentValue.isValue: return False else: for componentValue in self._componentValues: if componentValue is noValue or not componentValue.isValue: return False return True @property def isInconsistent(self): """Run necessary checks to ensure |ASN.1| object consistency. Default action is to verify |ASN.1| object against constraints imposed by `subtypeSpec`. Raises ------ :py:class:`~pyasn1.error.PyAsn1tError` on any inconsistencies found """ if self.componentType is noValue or not self.subtypeSpec: return False if self._componentValues is noValue: return True mapping = {} for idx, value in enumerate(self._componentValues): # Absent fields are not in the mapping if value is noValue: continue name = self.componentType.getNameByPosition(idx) mapping[name] = value try: # Represent Sequence/Set as a bare dict to constraints chain self.subtypeSpec(mapping) except error.PyAsn1Error as exc: return exc return False def prettyPrint(self, scope=0): """Return an object representation string. Returns ------- : :class:`str` Human-friendly object representation. """ scope += 1 representation = self.__class__.__name__ + ':\n' for idx, componentValue in enumerate(self._componentValues): if componentValue is not noValue and componentValue.isValue: representation += ' ' * scope if self.componentType: representation += self.componentType.getNameByPosition(idx) else: representation += self._dynamicNames.getNameByPosition(idx) representation = '%s=%s\n' % ( representation, componentValue.prettyPrint(scope) ) return representation def prettyPrintType(self, scope=0): scope += 1 representation = '%s -> %s {\n' % (self.tagSet, self.__class__.__name__) for idx, componentType in enumerate(self.componentType.values() or self._componentValues): representation += ' ' * scope if self.componentType: representation += '"%s"' % self.componentType.getNameByPosition(idx) else: representation += '"%s"' % self._dynamicNames.getNameByPosition(idx) representation = '%s = %s\n' % ( representation, componentType.prettyPrintType(scope) ) return representation + '\n' + ' ' * (scope - 1) + '}' # backward compatibility def setDefaultComponents(self): return self def getComponentType(self): if self._componentTypeLen: return self.componentType def getNameByPosition(self, idx): if self._componentTypeLen: return self.componentType[idx].name class Sequence(SequenceAndSetBase): __doc__ = SequenceAndSetBase.__doc__ #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x10) ) #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object #: imposing constraints on |ASN.1| type initialization values. subtypeSpec = constraint.ConstraintsIntersection() #: Default collection of ASN.1 types of component (e.g. :py:class:`~pyasn1.type.namedtype.NamedType`) #: object imposing size constraint on |ASN.1| objects componentType = namedtype.NamedTypes() # Disambiguation ASN.1 types identification typeId = SequenceAndSetBase.getTypeId() # backward compatibility def getComponentTagMapNearPosition(self, idx): if self.componentType: return self.componentType.getTagMapNearPosition(idx) def getComponentPositionNearType(self, tagSet, idx): if self.componentType: return self.componentType.getPositionNearType(tagSet, idx) else: return idx class Set(SequenceAndSetBase): __doc__ = SequenceAndSetBase.__doc__ #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x11) ) #: Default collection of ASN.1 types of component (e.g. :py:class:`~pyasn1.type.namedtype.NamedType`) #: object representing ASN.1 type allowed within |ASN.1| type componentType = namedtype.NamedTypes() #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object #: imposing constraints on |ASN.1| type initialization values. subtypeSpec = constraint.ConstraintsIntersection() # Disambiguation ASN.1 types identification typeId = SequenceAndSetBase.getTypeId() def getComponent(self, innerFlag=False): return self def getComponentByType(self, tagSet, default=noValue, instantiate=True, innerFlag=False): """Returns |ASN.1| type component by ASN.1 tag. Parameters ---------- tagSet : :py:class:`~pyasn1.type.tag.TagSet` Object representing ASN.1 tags to identify one of |ASN.1| object component Keyword Args ------------ default: :class:`object` If set and requested component is a schema object, return the `default` object instead of the requested component. instantiate: :class:`bool` If :obj:`True` (default), inner component will be automatically instantiated. If :obj:`False` either existing component or the :class:`noValue` object will be returned. Returns ------- : :py:class:`~pyasn1.type.base.PyAsn1Item` a pyasn1 object """ componentValue = self.getComponentByPosition( self.componentType.getPositionByType(tagSet), default=default, instantiate=instantiate ) if innerFlag and isinstance(componentValue, Set): # get inner component by inner tagSet return componentValue.getComponent(innerFlag=True) else: # get outer component by inner tagSet return componentValue def setComponentByType(self, tagSet, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True, innerFlag=False): """Assign |ASN.1| type component by ASN.1 tag. Parameters ---------- tagSet : :py:class:`~pyasn1.type.tag.TagSet` Object representing ASN.1 tags to identify one of |ASN.1| object component Keyword Args ------------ value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentType* is set) or ASN.1 value object to assign to |ASN.1| component. If `value` is not given, schema object will be set as a component. verifyConstraints : :class:`bool` If :obj:`False`, skip constraints validation matchTags: :class:`bool` If :obj:`False`, skip component tags matching matchConstraints: :class:`bool` If :obj:`False`, skip component constraints matching innerFlag: :class:`bool` If :obj:`True`, search for matching *tagSet* recursively. Returns ------- self """ idx = self.componentType.getPositionByType(tagSet) if innerFlag: # set inner component by inner tagSet componentType = self.componentType.getTypeByPosition(idx) if componentType.tagSet: return self.setComponentByPosition( idx, value, verifyConstraints, matchTags, matchConstraints ) else: componentType = self.getComponentByPosition(idx) return componentType.setComponentByType( tagSet, value, verifyConstraints, matchTags, matchConstraints, innerFlag=innerFlag ) else: # set outer component by inner tagSet return self.setComponentByPosition( idx, value, verifyConstraints, matchTags, matchConstraints ) @property def componentTagMap(self): if self.componentType: return self.componentType.tagMapUnique class Choice(Set): """Create |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.ConstructedAsn1Type`, its objects are mutable and duck-type Python :class:`list` objects. Keyword Args ------------ componentType: :py:class:`~pyasn1.type.namedtype.NamedType` Object holding named ASN.1 types allowed within this collection tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s). Constraints verification for |ASN.1| type can only occur on explicit `.isInconsistent` call. Examples -------- .. code-block:: python class Afters(Choice): ''' ASN.1 specification: Afters ::= CHOICE { cheese [0] IA5String, dessert [1] IA5String } ''' componentType = NamedTypes( NamedType('cheese', IA5String().subtype( implicitTag=Tag(tagClassContext, tagFormatSimple, 0) ), NamedType('dessert', IA5String().subtype( implicitTag=Tag(tagClassContext, tagFormatSimple, 1) ) ) afters = Afters() afters['cheese'] = 'Mascarpone' """ #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = tag.TagSet() # untagged #: Default collection of ASN.1 types of component (e.g. :py:class:`~pyasn1.type.namedtype.NamedType`) #: object representing ASN.1 type allowed within |ASN.1| type componentType = namedtype.NamedTypes() #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object #: imposing constraints on |ASN.1| type initialization values. subtypeSpec = constraint.ConstraintsIntersection( constraint.ValueSizeConstraint(1, 1) ) # Disambiguation ASN.1 types identification typeId = Set.getTypeId() _currentIdx = None def __eq__(self, other): if self._componentValues: return self._componentValues[self._currentIdx] == other return NotImplemented def __ne__(self, other): if self._componentValues: return self._componentValues[self._currentIdx] != other return NotImplemented def __lt__(self, other): if self._componentValues: return self._componentValues[self._currentIdx] < other return NotImplemented def __le__(self, other): if self._componentValues: return self._componentValues[self._currentIdx] <= other return NotImplemented def __gt__(self, other): if self._componentValues: return self._componentValues[self._currentIdx] > other return NotImplemented def __ge__(self, other): if self._componentValues: return self._componentValues[self._currentIdx] >= other return NotImplemented def __bool__(self): return bool(self._componentValues) def __len__(self): return self._currentIdx is not None and 1 or 0 def __contains__(self, key): if self._currentIdx is None: return False return key == self.componentType[self._currentIdx].getName() def __iter__(self): if self._currentIdx is None: raise StopIteration yield self.componentType[self._currentIdx].getName() # Python dict protocol def values(self): if self._currentIdx is not None: yield self._componentValues[self._currentIdx] def keys(self): if self._currentIdx is not None: yield self.componentType[self._currentIdx].getName() def items(self): if self._currentIdx is not None: yield self.componentType[self._currentIdx].getName(), self[self._currentIdx] def checkConsistency(self): if self._currentIdx is None: raise error.PyAsn1Error('Component not chosen') def _cloneComponentValues(self, myClone, cloneValueFlag): try: component = self.getComponent() except error.PyAsn1Error: pass else: if isinstance(component, Choice): tagSet = component.effectiveTagSet else: tagSet = component.tagSet if isinstance(component, base.ConstructedAsn1Type): myClone.setComponentByType( tagSet, component.clone(cloneValueFlag=cloneValueFlag) ) else: myClone.setComponentByType(tagSet, component.clone()) def getComponentByPosition(self, idx, default=noValue, instantiate=True): __doc__ = Set.__doc__ if self._currentIdx is None or self._currentIdx != idx: return Set.getComponentByPosition(self, idx, default=default, instantiate=instantiate) return self._componentValues[idx] def setComponentByPosition(self, idx, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True): """Assign |ASN.1| type component by position. Equivalent to Python sequence item assignment operation (e.g. `[]`). Parameters ---------- idx: :class:`int` Component index (zero-based). Must either refer to existing component or to N+1 component. In the latter case a new component type gets instantiated (if *componentType* is set, or given ASN.1 object is taken otherwise) and appended to the |ASN.1| sequence. Keyword Args ------------ value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentType* is set) or ASN.1 value object to assign to |ASN.1| component. Once a new value is set to *idx* component, previous value is dropped. If `value` is not given, schema object will be set as a component. verifyConstraints : :class:`bool` If :obj:`False`, skip constraints validation matchTags: :class:`bool` If :obj:`False`, skip component tags matching matchConstraints: :class:`bool` If :obj:`False`, skip component constraints matching Returns ------- self """ oldIdx = self._currentIdx Set.setComponentByPosition(self, idx, value, verifyConstraints, matchTags, matchConstraints) self._currentIdx = idx if oldIdx is not None and oldIdx != idx: self._componentValues[oldIdx] = noValue return self @property def effectiveTagSet(self): """Return a :class:`~pyasn1.type.tag.TagSet` object of the currently initialized component or self (if |ASN.1| is tagged).""" if self.tagSet: return self.tagSet else: component = self.getComponent() return component.effectiveTagSet @property def tagMap(self): """"Return a :class:`~pyasn1.type.tagmap.TagMap` object mapping ASN.1 tags to ASN.1 objects contained within callee. """ if self.tagSet: return Set.tagMap.fget(self) else: return self.componentType.tagMapUnique def getComponent(self, innerFlag=False): """Return currently assigned component of the |ASN.1| object. Returns ------- : :py:class:`~pyasn1.type.base.PyAsn1Item` a PyASN1 object """ if self._currentIdx is None: raise error.PyAsn1Error('Component not chosen') else: c = self._componentValues[self._currentIdx] if innerFlag and isinstance(c, Choice): return c.getComponent(innerFlag) else: return c def getName(self, innerFlag=False): """Return the name of currently assigned component of the |ASN.1| object. Returns ------- : :py:class:`str` |ASN.1| component name """ if self._currentIdx is None: raise error.PyAsn1Error('Component not chosen') else: if innerFlag: c = self._componentValues[self._currentIdx] if isinstance(c, Choice): return c.getName(innerFlag) return self.componentType.getNameByPosition(self._currentIdx) @property def isValue(self): """Indicate that |ASN.1| object represents ASN.1 value. If *isValue* is :obj:`False` then this object represents just ASN.1 schema. If *isValue* is :obj:`True` then, in addition to its ASN.1 schema features, this object can also be used like a Python built-in object (e.g. :class:`int`, :class:`str`, :class:`dict` etc.). Returns ------- : :class:`bool` :obj:`False` if object represents just ASN.1 schema. :obj:`True` if object represents ASN.1 schema and can be used as a normal value. Note ---- There is an important distinction between PyASN1 schema and value objects. The PyASN1 schema objects can only participate in ASN.1 schema-related operations (e.g. defining or testing the structure of the data). Most obvious uses of ASN.1 schema is to guide serialisation codecs whilst encoding/decoding serialised ASN.1 contents. The PyASN1 value objects can **additionally** participate in many operations involving regular Python objects (e.g. arithmetic, comprehension etc). """ if self._currentIdx is None: return False componentValue = self._componentValues[self._currentIdx] return componentValue is not noValue and componentValue.isValue def clear(self): self._currentIdx = None return Set.clear(self) # compatibility stubs def getMinTagSet(self): return self.minTagSet class Any(OctetString): """Create |ASN.1| schema or value object. |ASN.1| class is based on :class:`~pyasn1.type.base.SimpleAsn1Type`, its objects are immutable and duck-type :class:`bytes`. When used in Unicode context, |ASN.1| type assumes "|encoding|" serialisation. Keyword Args ------------ value: :class:`unicode`, :class:`str`, :class:`bytes` or |ASN.1| object :class:`bytes`, alternatively :class:`str` representing character string to be serialised into octets (note `encoding` parameter) or |ASN.1| object. If `value` is not given, schema object will be created. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s). Constraints verification for |ASN.1| type occurs automatically on object instantiation. encoding: :py:class:`str` Unicode codec ID to encode/decode :class:`str` the payload when |ASN.1| object is used in text string context. binValue: :py:class:`str` Binary string initializer to use instead of the *value*. Example: '10110011'. hexValue: :py:class:`str` Hexadecimal string initializer to use instead of the *value*. Example: 'DEADBEEF'. Raises ------ ~pyasn1.error.ValueConstraintError, ~pyasn1.error.PyAsn1Error On constraint violation or bad initializer. Examples -------- .. code-block:: python class Error(Sequence): ''' ASN.1 specification: Error ::= SEQUENCE { code INTEGER, parameter ANY DEFINED BY code -- Either INTEGER or REAL } ''' componentType=NamedTypes( NamedType('code', Integer()), NamedType('parameter', Any(), openType=OpenType('code', {1: Integer(), 2: Real()})) ) error = Error() error['code'] = 1 error['parameter'] = Integer(1234) """ #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.tag.TagSet` object representing ASN.1 tag(s) #: associated with |ASN.1| type. tagSet = tag.TagSet() # untagged #: Set (on class, not on instance) or return a #: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` object #: imposing constraints on |ASN.1| type initialization values. subtypeSpec = constraint.ConstraintsIntersection() # Disambiguation ASN.1 types identification typeId = OctetString.getTypeId() @property def tagMap(self): """"Return a :class:`~pyasn1.type.tagmap.TagMap` object mapping ASN.1 tags to ASN.1 objects contained within callee. """ try: return self._tagMap except AttributeError: self._tagMap = tagmap.TagMap( {self.tagSet: self}, {eoo.endOfOctets.tagSet: eoo.endOfOctets}, self ) return self._tagMap # XXX # coercion rules? PK!鎴波 useful.pynu刐迭# # This file is part of pyasn1 software. # # Copyright (c) 2005-2020, Ilya Etingof # License: https://pyasn1.readthedocs.io/en/latest/license.html # import datetime from pyasn1 import error from pyasn1.type import char from pyasn1.type import tag from pyasn1.type import univ __all__ = ['ObjectDescriptor', 'GeneralizedTime', 'UTCTime'] NoValue = univ.NoValue noValue = univ.noValue class ObjectDescriptor(char.GraphicString): __doc__ = char.GraphicString.__doc__ #: Default :py:class:`~pyasn1.type.tag.TagSet` object for |ASN.1| objects tagSet = char.GraphicString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 7) ) # Optimization for faster codec lookup typeId = char.GraphicString.getTypeId() class TimeMixIn(object): _yearsDigits = 4 _hasSubsecond = False _optionalMinutes = False _shortTZ = False class FixedOffset(datetime.tzinfo): """Fixed offset in minutes east from UTC.""" # defaulted arguments required # https: // docs.python.org / 2.3 / lib / datetime - tzinfo.html def __init__(self, offset=0, name='UTC'): self.__offset = datetime.timedelta(minutes=offset) self.__name = name def utcoffset(self, dt): return self.__offset def tzname(self, dt): return self.__name def dst(self, dt): return datetime.timedelta(0) UTC = FixedOffset() @property def asDateTime(self): """Create :py:class:`datetime.datetime` object from a |ASN.1| object. Returns ------- : new instance of :py:class:`datetime.datetime` object """ text = str(self) if text.endswith('Z'): tzinfo = TimeMixIn.UTC text = text[:-1] elif '-' in text or '+' in text: if '+' in text: text, plusminus, tz = text.partition('+') else: text, plusminus, tz = text.partition('-') if self._shortTZ and len(tz) == 2: tz += '00' if len(tz) != 4: raise error.PyAsn1Error('malformed time zone offset %s' % tz) try: minutes = int(tz[:2]) * 60 + int(tz[2:]) if plusminus == '-': minutes *= -1 except ValueError: raise error.PyAsn1Error('unknown time specification %s' % self) tzinfo = TimeMixIn.FixedOffset(minutes, '?') else: tzinfo = None if '.' in text or ',' in text: if '.' in text: text, _, ms = text.partition('.') else: text, _, ms = text.partition(',') try: ms = int(ms) * 1000 except ValueError: raise error.PyAsn1Error('bad sub-second time specification %s' % self) else: ms = 0 if self._optionalMinutes and len(text) - self._yearsDigits == 6: text += '0000' elif len(text) - self._yearsDigits == 8: text += '00' try: dt = datetime.datetime.strptime(text, self._yearsDigits == 4 and '%Y%m%d%H%M%S' or '%y%m%d%H%M%S') except ValueError: raise error.PyAsn1Error('malformed datetime format %s' % self) return dt.replace(microsecond=ms, tzinfo=tzinfo) @classmethod def fromDateTime(cls, dt): """Create |ASN.1| object from a :py:class:`datetime.datetime` object. Parameters ---------- dt: :py:class:`datetime.datetime` object The `datetime.datetime` object to initialize the |ASN.1| object from Returns ------- : new instance of |ASN.1| value """ text = dt.strftime(cls._yearsDigits == 4 and '%Y%m%d%H%M%S' or '%y%m%d%H%M%S') if cls._hasSubsecond: text += '.%d' % (dt.microsecond // 1000) if dt.utcoffset(): seconds = dt.utcoffset().seconds if seconds < 0: text += '-' else: text += '+' text += '%.2d%.2d' % (seconds // 3600, seconds % 3600) else: text += 'Z' return cls(text) class GeneralizedTime(char.VisibleString, TimeMixIn): __doc__ = char.VisibleString.__doc__ #: Default :py:class:`~pyasn1.type.tag.TagSet` object for |ASN.1| objects tagSet = char.VisibleString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 24) ) # Optimization for faster codec lookup typeId = char.VideotexString.getTypeId() _yearsDigits = 4 _hasSubsecond = True _optionalMinutes = True _shortTZ = True class UTCTime(char.VisibleString, TimeMixIn): __doc__ = char.VisibleString.__doc__ #: Default :py:class:`~pyasn1.type.tag.TagSet` object for |ASN.1| objects tagSet = char.VisibleString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 23) ) # Optimization for faster codec lookup typeId = char.VideotexString.getTypeId() _yearsDigits = 2 _hasSubsecond = False _optionalMinutes = False _shortTZ = False PK!D@匯;; __init__.pynu刐迭# This file is necessary to make this directory a package. PK!f3?3? namedtype.pynu刐迭# # This file is part of pyasn1 software. # # Copyright (c) 2005-2020, Ilya Etingof # License: https://pyasn1.readthedocs.io/en/latest/license.html # import sys from pyasn1 import error from pyasn1.type import tag from pyasn1.type import tagmap __all__ = ['NamedType', 'OptionalNamedType', 'DefaultedNamedType', 'NamedTypes'] class NamedType(object): """Create named field object for a constructed ASN.1 type. The |NamedType| object represents a single name and ASN.1 type of a constructed ASN.1 type. |NamedType| objects are immutable and duck-type Python :class:`tuple` objects holding *name* and *asn1Object* components. Parameters ---------- name: :py:class:`str` Field name asn1Object: ASN.1 type object """ isOptional = False isDefaulted = False def __init__(self, name, asn1Object, openType=None): self.__name = name self.__type = asn1Object self.__nameAndType = name, asn1Object self.__openType = openType def __repr__(self): representation = '%s=%r' % (self.name, self.asn1Object) if self.openType: representation += ', open type %r' % self.openType return '<%s object, type %s>' % ( self.__class__.__name__, representation) def __eq__(self, other): return self.__nameAndType == other def __ne__(self, other): return self.__nameAndType != other def __lt__(self, other): return self.__nameAndType < other def __le__(self, other): return self.__nameAndType <= other def __gt__(self, other): return self.__nameAndType > other def __ge__(self, other): return self.__nameAndType >= other def __hash__(self): return hash(self.__nameAndType) def __getitem__(self, idx): return self.__nameAndType[idx] def __iter__(self): return iter(self.__nameAndType) @property def name(self): return self.__name @property def asn1Object(self): return self.__type @property def openType(self): return self.__openType # Backward compatibility def getName(self): return self.name def getType(self): return self.asn1Object class OptionalNamedType(NamedType): __doc__ = NamedType.__doc__ isOptional = True class DefaultedNamedType(NamedType): __doc__ = NamedType.__doc__ isDefaulted = True class NamedTypes(object): """Create a collection of named fields for a constructed ASN.1 type. The NamedTypes object represents a collection of named fields of a constructed ASN.1 type. *NamedTypes* objects are immutable and duck-type Python :class:`dict` objects holding *name* as keys and ASN.1 type object as values. Parameters ---------- *namedTypes: :class:`~pyasn1.type.namedtype.NamedType` Examples -------- .. code-block:: python class Description(Sequence): ''' ASN.1 specification: Description ::= SEQUENCE { surname IA5String, first-name IA5String OPTIONAL, age INTEGER DEFAULT 40 } ''' componentType = NamedTypes( NamedType('surname', IA5String()), OptionalNamedType('first-name', IA5String()), DefaultedNamedType('age', Integer(40)) ) descr = Description() descr['surname'] = 'Smith' descr['first-name'] = 'John' """ def __init__(self, *namedTypes, **kwargs): self.__namedTypes = namedTypes self.__namedTypesLen = len(self.__namedTypes) self.__minTagSet = self.__computeMinTagSet() self.__nameToPosMap = self.__computeNameToPosMap() self.__tagToPosMap = self.__computeTagToPosMap() self.__ambiguousTypes = 'terminal' not in kwargs and self.__computeAmbiguousTypes() or {} self.__uniqueTagMap = self.__computeTagMaps(unique=True) self.__nonUniqueTagMap = self.__computeTagMaps(unique=False) self.__hasOptionalOrDefault = any([True for namedType in self.__namedTypes if namedType.isDefaulted or namedType.isOptional]) self.__hasOpenTypes = any([True for namedType in self.__namedTypes if namedType.openType]) self.__requiredComponents = frozenset( [idx for idx, nt in enumerate(self.__namedTypes) if not nt.isOptional and not nt.isDefaulted] ) self.__keys = frozenset([namedType.name for namedType in self.__namedTypes]) self.__values = tuple([namedType.asn1Object for namedType in self.__namedTypes]) self.__items = tuple([(namedType.name, namedType.asn1Object) for namedType in self.__namedTypes]) def __repr__(self): representation = ', '.join(['%r' % x for x in self.__namedTypes]) return '<%s object, types %s>' % ( self.__class__.__name__, representation) def __eq__(self, other): return self.__namedTypes == other def __ne__(self, other): return self.__namedTypes != other def __lt__(self, other): return self.__namedTypes < other def __le__(self, other): return self.__namedTypes <= other def __gt__(self, other): return self.__namedTypes > other def __ge__(self, other): return self.__namedTypes >= other def __hash__(self): return hash(self.__namedTypes) def __getitem__(self, idx): try: return self.__namedTypes[idx] except TypeError: return self.__namedTypes[self.__nameToPosMap[idx]] def __contains__(self, key): return key in self.__nameToPosMap def __iter__(self): return (x[0] for x in self.__namedTypes) def __bool__(self): return self.__namedTypesLen > 0 def __len__(self): return self.__namedTypesLen # Python dict protocol def values(self): return self.__values def keys(self): return self.__keys def items(self): return self.__items def clone(self): return self.__class__(*self.__namedTypes) class PostponedError(object): def __init__(self, errorMsg): self.__errorMsg = errorMsg def __getitem__(self, item): raise error.PyAsn1Error(self.__errorMsg) def __computeTagToPosMap(self): tagToPosMap = {} for idx, namedType in enumerate(self.__namedTypes): tagMap = namedType.asn1Object.tagMap if isinstance(tagMap, NamedTypes.PostponedError): return tagMap if not tagMap: continue for _tagSet in tagMap.presentTypes: if _tagSet in tagToPosMap: return NamedTypes.PostponedError('Duplicate component tag %s at %s' % (_tagSet, namedType)) tagToPosMap[_tagSet] = idx return tagToPosMap def __computeNameToPosMap(self): nameToPosMap = {} for idx, namedType in enumerate(self.__namedTypes): if namedType.name in nameToPosMap: return NamedTypes.PostponedError('Duplicate component name %s at %s' % (namedType.name, namedType)) nameToPosMap[namedType.name] = idx return nameToPosMap def __computeAmbiguousTypes(self): ambiguousTypes = {} partialAmbiguousTypes = () for idx, namedType in reversed(tuple(enumerate(self.__namedTypes))): if namedType.isOptional or namedType.isDefaulted: partialAmbiguousTypes = (namedType,) + partialAmbiguousTypes else: partialAmbiguousTypes = (namedType,) if len(partialAmbiguousTypes) == len(self.__namedTypes): ambiguousTypes[idx] = self else: ambiguousTypes[idx] = NamedTypes(*partialAmbiguousTypes, **dict(terminal=True)) return ambiguousTypes def getTypeByPosition(self, idx): """Return ASN.1 type object by its position in fields set. Parameters ---------- idx: :py:class:`int` Field index Returns ------- : ASN.1 type Raises ------ ~pyasn1.error.PyAsn1Error If given position is out of fields range """ try: return self.__namedTypes[idx].asn1Object except IndexError: raise error.PyAsn1Error('Type position out of range') def getPositionByType(self, tagSet): """Return field position by its ASN.1 type. Parameters ---------- tagSet: :class:`~pysnmp.type.tag.TagSet` ASN.1 tag set distinguishing one ASN.1 type from others. Returns ------- : :py:class:`int` ASN.1 type position in fields set Raises ------ ~pyasn1.error.PyAsn1Error If *tagSet* is not present or ASN.1 types are not unique within callee *NamedTypes* """ try: return self.__tagToPosMap[tagSet] except KeyError: raise error.PyAsn1Error('Type %s not found' % (tagSet,)) def getNameByPosition(self, idx): """Return field name by its position in fields set. Parameters ---------- idx: :py:class:`idx` Field index Returns ------- : :py:class:`str` Field name Raises ------ ~pyasn1.error.PyAsn1Error If given field name is not present in callee *NamedTypes* """ try: return self.__namedTypes[idx].name except IndexError: raise error.PyAsn1Error('Type position out of range') def getPositionByName(self, name): """Return field position by filed name. Parameters ---------- name: :py:class:`str` Field name Returns ------- : :py:class:`int` Field position in fields set Raises ------ ~pyasn1.error.PyAsn1Error If *name* is not present or not unique within callee *NamedTypes* """ try: return self.__nameToPosMap[name] except KeyError: raise error.PyAsn1Error('Name %s not found' % (name,)) def getTagMapNearPosition(self, idx): """Return ASN.1 types that are allowed at or past given field position. Some ASN.1 serialisation allow for skipping optional and defaulted fields. Some constructed ASN.1 types allow reordering of the fields. When recovering such objects it may be important to know which types can possibly be present at any given position in the field sets. Parameters ---------- idx: :py:class:`int` Field index Returns ------- : :class:`~pyasn1.type.tagmap.TagMap` Map if ASN.1 types allowed at given field position Raises ------ ~pyasn1.error.PyAsn1Error If given position is out of fields range """ try: return self.__ambiguousTypes[idx].tagMap except KeyError: raise error.PyAsn1Error('Type position out of range') def getPositionNearType(self, tagSet, idx): """Return the closest field position where given ASN.1 type is allowed. Some ASN.1 serialisation allow for skipping optional and defaulted fields. Some constructed ASN.1 types allow reordering of the fields. When recovering such objects it may be important to know at which field position, in field set, given *tagSet* is allowed at or past *idx* position. Parameters ---------- tagSet: :class:`~pyasn1.type.tag.TagSet` ASN.1 type which field position to look up idx: :py:class:`int` Field position at or past which to perform ASN.1 type look up Returns ------- : :py:class:`int` Field position in fields set Raises ------ ~pyasn1.error.PyAsn1Error If *tagSet* is not present or not unique within callee *NamedTypes* or *idx* is out of fields range """ try: return idx + self.__ambiguousTypes[idx].getPositionByType(tagSet) except KeyError: raise error.PyAsn1Error('Type position out of range') def __computeMinTagSet(self): minTagSet = None for namedType in self.__namedTypes: asn1Object = namedType.asn1Object try: tagSet = asn1Object.minTagSet except AttributeError: tagSet = asn1Object.tagSet if minTagSet is None or tagSet < minTagSet: minTagSet = tagSet return minTagSet or tag.TagSet() @property def minTagSet(self): """Return the minimal TagSet among ASN.1 type in callee *NamedTypes*. Some ASN.1 types/serialisation protocols require ASN.1 types to be arranged based on their numerical tag value. The *minTagSet* property returns that. Returns ------- : :class:`~pyasn1.type.tagset.TagSet` Minimal TagSet among ASN.1 types in callee *NamedTypes* """ return self.__minTagSet def __computeTagMaps(self, unique): presentTypes = {} skipTypes = {} defaultType = None for namedType in self.__namedTypes: tagMap = namedType.asn1Object.tagMap if isinstance(tagMap, NamedTypes.PostponedError): return tagMap for tagSet in tagMap: if unique and tagSet in presentTypes: return NamedTypes.PostponedError('Non-unique tagSet %s of %s at %s' % (tagSet, namedType, self)) presentTypes[tagSet] = namedType.asn1Object skipTypes.update(tagMap.skipTypes) if defaultType is None: defaultType = tagMap.defaultType elif tagMap.defaultType is not None: return NamedTypes.PostponedError('Duplicate default ASN.1 type at %s' % (self,)) return tagmap.TagMap(presentTypes, skipTypes, defaultType) @property def tagMap(self): """Return a *TagMap* object from tags and types recursively. Return a :class:`~pyasn1.type.tagmap.TagMap` object by combining tags from *TagMap* objects of children types and associating them with their immediate child type. Example ------- .. code-block:: python OuterType ::= CHOICE { innerType INTEGER } Calling *.tagMap* on *OuterType* will yield a map like this: .. code-block:: python Integer.tagSet -> Choice """ return self.__nonUniqueTagMap @property def tagMapUnique(self): """Return a *TagMap* object from unique tags and types recursively. Return a :class:`~pyasn1.type.tagmap.TagMap` object by combining tags from *TagMap* objects of children types and associating them with their immediate child type. Example ------- .. code-block:: python OuterType ::= CHOICE { innerType INTEGER } Calling *.tagMapUnique* on *OuterType* will yield a map like this: .. code-block:: python Integer.tagSet -> Choice Note ---- Duplicate *TagSet* objects found in the tree of children types would cause error. """ return self.__uniqueTagMap @property def hasOptionalOrDefault(self): return self.__hasOptionalOrDefault @property def hasOpenTypes(self): return self.__hasOpenTypes @property def namedTypes(self): return tuple(self.__namedTypes) @property def requiredComponents(self): return self.__requiredComponents PK!%%tag.pynu刐迭# # This file is part of pyasn1 software. # # Copyright (c) 2005-2020, Ilya Etingof # License: https://pyasn1.readthedocs.io/en/latest/license.html # from pyasn1 import error __all__ = ['tagClassUniversal', 'tagClassApplication', 'tagClassContext', 'tagClassPrivate', 'tagFormatSimple', 'tagFormatConstructed', 'tagCategoryImplicit', 'tagCategoryExplicit', 'tagCategoryUntagged', 'Tag', 'TagSet'] #: Identifier for ASN.1 class UNIVERSAL tagClassUniversal = 0x00 #: Identifier for ASN.1 class APPLICATION tagClassApplication = 0x40 #: Identifier for ASN.1 class context-specific tagClassContext = 0x80 #: Identifier for ASN.1 class private tagClassPrivate = 0xC0 #: Identifier for "simple" ASN.1 structure (e.g. scalar) tagFormatSimple = 0x00 #: Identifier for "constructed" ASN.1 structure (e.g. may have inner components) tagFormatConstructed = 0x20 tagCategoryImplicit = 0x01 tagCategoryExplicit = 0x02 tagCategoryUntagged = 0x04 class Tag(object): """Create ASN.1 tag Represents ASN.1 tag that can be attached to a ASN.1 type to make types distinguishable from each other. *Tag* objects are immutable and duck-type Python :class:`tuple` objects holding three integer components of a tag. Parameters ---------- tagClass: :py:class:`int` Tag *class* value tagFormat: :py:class:`int` Tag *format* value tagId: :py:class:`int` Tag ID value """ def __init__(self, tagClass, tagFormat, tagId): if tagId < 0: raise error.PyAsn1Error('Negative tag ID (%s) not allowed' % tagId) self.__tagClass = tagClass self.__tagFormat = tagFormat self.__tagId = tagId self.__tagClassId = tagClass, tagId self.__hash = hash(self.__tagClassId) def __repr__(self): representation = '[%s:%s:%s]' % ( self.__tagClass, self.__tagFormat, self.__tagId) return '<%s object, tag %s>' % ( self.__class__.__name__, representation) def __eq__(self, other): return self.__tagClassId == other def __ne__(self, other): return self.__tagClassId != other def __lt__(self, other): return self.__tagClassId < other def __le__(self, other): return self.__tagClassId <= other def __gt__(self, other): return self.__tagClassId > other def __ge__(self, other): return self.__tagClassId >= other def __hash__(self): return self.__hash def __getitem__(self, idx): if idx == 0: return self.__tagClass elif idx == 1: return self.__tagFormat elif idx == 2: return self.__tagId else: raise IndexError def __iter__(self): yield self.__tagClass yield self.__tagFormat yield self.__tagId def __and__(self, otherTag): return self.__class__(self.__tagClass & otherTag.tagClass, self.__tagFormat & otherTag.tagFormat, self.__tagId & otherTag.tagId) def __or__(self, otherTag): return self.__class__(self.__tagClass | otherTag.tagClass, self.__tagFormat | otherTag.tagFormat, self.__tagId | otherTag.tagId) @property def tagClass(self): """ASN.1 tag class Returns ------- : :py:class:`int` Tag class """ return self.__tagClass @property def tagFormat(self): """ASN.1 tag format Returns ------- : :py:class:`int` Tag format """ return self.__tagFormat @property def tagId(self): """ASN.1 tag ID Returns ------- : :py:class:`int` Tag ID """ return self.__tagId class TagSet(object): """Create a collection of ASN.1 tags Represents a combination of :class:`~pyasn1.type.tag.Tag` objects that can be attached to a ASN.1 type to make types distinguishable from each other. *TagSet* objects are immutable and duck-type Python :class:`tuple` objects holding arbitrary number of :class:`~pyasn1.type.tag.Tag` objects. Parameters ---------- baseTag: :class:`~pyasn1.type.tag.Tag` Base *Tag* object. This tag survives IMPLICIT tagging. *superTags: :class:`~pyasn1.type.tag.Tag` Additional *Tag* objects taking part in subtyping. Examples -------- .. code-block:: python class OrderNumber(NumericString): ''' ASN.1 specification Order-number ::= [APPLICATION 5] IMPLICIT NumericString ''' tagSet = NumericString.tagSet.tagImplicitly( Tag(tagClassApplication, tagFormatSimple, 5) ) orderNumber = OrderNumber('1234') """ def __init__(self, baseTag=(), *superTags): self.__baseTag = baseTag self.__superTags = superTags self.__superTagsClassId = tuple( [(superTag.tagClass, superTag.tagId) for superTag in superTags] ) self.__lenOfSuperTags = len(superTags) self.__hash = hash(self.__superTagsClassId) def __repr__(self): representation = '-'.join(['%s:%s:%s' % (x.tagClass, x.tagFormat, x.tagId) for x in self.__superTags]) if representation: representation = 'tags ' + representation else: representation = 'untagged' return '<%s object, %s>' % (self.__class__.__name__, representation) def __add__(self, superTag): return self.__class__(self.__baseTag, *self.__superTags + (superTag,)) def __radd__(self, superTag): return self.__class__(self.__baseTag, *(superTag,) + self.__superTags) def __getitem__(self, i): if i.__class__ is slice: return self.__class__(self.__baseTag, *self.__superTags[i]) else: return self.__superTags[i] def __eq__(self, other): return self.__superTagsClassId == other def __ne__(self, other): return self.__superTagsClassId != other def __lt__(self, other): return self.__superTagsClassId < other def __le__(self, other): return self.__superTagsClassId <= other def __gt__(self, other): return self.__superTagsClassId > other def __ge__(self, other): return self.__superTagsClassId >= other def __hash__(self): return self.__hash def __len__(self): return self.__lenOfSuperTags @property def baseTag(self): """Return base ASN.1 tag Returns ------- : :class:`~pyasn1.type.tag.Tag` Base tag of this *TagSet* """ return self.__baseTag @property def superTags(self): """Return ASN.1 tags Returns ------- : :py:class:`tuple` Tuple of :class:`~pyasn1.type.tag.Tag` objects that this *TagSet* contains """ return self.__superTags def tagExplicitly(self, superTag): """Return explicitly tagged *TagSet* Create a new *TagSet* representing callee *TagSet* explicitly tagged with passed tag(s). With explicit tagging mode, new tags are appended to existing tag(s). Parameters ---------- superTag: :class:`~pyasn1.type.tag.Tag` *Tag* object to tag this *TagSet* Returns ------- : :class:`~pyasn1.type.tag.TagSet` New *TagSet* object """ if superTag.tagClass == tagClassUniversal: raise error.PyAsn1Error("Can't tag with UNIVERSAL class tag") if superTag.tagFormat != tagFormatConstructed: superTag = Tag(superTag.tagClass, tagFormatConstructed, superTag.tagId) return self + superTag def tagImplicitly(self, superTag): """Return implicitly tagged *TagSet* Create a new *TagSet* representing callee *TagSet* implicitly tagged with passed tag(s). With implicit tagging mode, new tag(s) replace the last existing tag. Parameters ---------- superTag: :class:`~pyasn1.type.tag.Tag` *Tag* object to tag this *TagSet* Returns ------- : :class:`~pyasn1.type.tag.TagSet` New *TagSet* object """ if self.__superTags: superTag = Tag(superTag.tagClass, self.__superTags[-1].tagFormat, superTag.tagId) return self[:-1] + superTag def isSuperTagSetOf(self, tagSet): """Test type relationship against given *TagSet* The callee is considered to be a supertype of given *TagSet* tag-wise if all tags in *TagSet* are present in the callee and they are in the same order. Parameters ---------- tagSet: :class:`~pyasn1.type.tag.TagSet` *TagSet* object to evaluate against the callee Returns ------- : :py:class:`bool` :obj:`True` if callee is a supertype of *tagSet* """ if len(tagSet) < self.__lenOfSuperTags: return False return self.__superTags == tagSet[:self.__lenOfSuperTags] # Backward compatibility def getBaseTag(self): return self.__baseTag def initTagSet(tag): return TagSet(tag, tag) PK!4񗪴6 phpunit.xmlnu刐迭PK!h澭 qREADME.mdnu刐迭PK!蓾   phive.xmlnu刐迭PK!$惢1LICENSEnu刐迭PK!衟镻  tests/unit/IterableTypeTest.phpnu刐迭PK!3etests/unit/SimpleTypeTest.phpnu刐迭PK!Z[vAaa$*tests/unit/GenericObjectTypeTest.phpnu刐迭PK!皴3tests/unit/NullTypeTest.phpnu刐迭PK!'紳dd:tests/unit/TypeNameTest.phpnu刐迭PK! 籽BCtests/unit/TypeTest.phpnu刐迭PK! )2''ZStests/unit/CallableTypeTest.phpnu刐迭PK!浚,衏tests/unit/UnknownTypeTest.phpnu刐迭PK!u挒綍琲tests/unit/VoidTypeTest.phpnu刐迭PK!*琛摳宲tests/unit/ObjectTypeTest.phpnu刐迭PK!瓌Luu憖tests/_fixture/ParentClass.phpnu刐迭PK!櫬N藠(Ttests/_fixture/ClassWithInvokeMethod.phpnu刐迭PK! 8\\6tests/_fixture/ChildClass.phpnu刐迭PK!誥!ZZ$邊tests/_fixture/callback_function.phpnu刐迭PK!+崌tests/_fixture/ClassWithCallbackMethods.phpnu刐迭PK!瓅饔KK綁tests/_fixture/Iterator.phpnu刐迭PK!謣d S.travis.ymlnu刐迭PK!o匵B d.php_cs.distnu刐迭PK!蝒伙cc 3composer.jsonnu刐迭PK!1酳)拥.github/FUNDING.ymlnu刐迭PK!W/400 *ChangeLog.mdnu刐迭PK!蜰>柡src/TypeName.phpnu刐迭PK!)T[[盍src/VoidType.phpnu刐迭PK!彻璹QQ壞src/IterableType.phpnu刐迭PK!9誳闧[src/NullType.phpnu刐迭PK!艠1咤雇src/ObjectType.phpnu刐迭PK!螉]練嘤src/CallableType.phpnu刐迭PK!k5 惧src/Type.phpnu刐迭PK!56媴ww"蹴src/exception/RuntimeException.phpnu刐迭PK!Pm{??撅src/exception/Exception.phpnu刐迭PK!Hsrc/GenericObjectType.phpnu刐迭PK! 猾EEksrc/UnknownType.phpnu刐迭PK!g 篦src/SimpleType.phpnu刐迭PK!罨 psalm.xmlnu刐迭PK!鳘霉 [build.xmlnu刐迭PK!拿e9 .gitattributesnu刐迭PK!婰馅  .gitignorenu刐迭PK!惀|xerror.pynu刐迭PK!縚錄U沀 :constraint.pynu刐迭PK!窬舕 htagmap.pynu刐迭PK!鮏繲- - topentype.pynu刐迭PK!捧钮"k__pycache__/useful.cpython-311.pycnu刐迭PK!'Κ&& b__pycache__/univ.cpython-311.pycnu刐迭PK!= 柚鑡鑡 赡__pycache__/base.cpython-311.pycnu刐迭PK!j,盼$7__pycache__/__init__.cpython-311.pycnu刐迭PK!雐gg!68__pycache__/error.cpython-311.pycnu刐迭PK!2顥$:__pycache__/opentype.cpython-311.pycnu刐迭PK!茊凭|4|4貸__pycache__/tag.cpython-311.pycnu刐迭PK!|莂cac%__pycache__/namedtype.cpython-311.pycnu刐迭PK!4譏紆紆&Z__pycache__/constraint.cpython-311.pycnu刐迭PK!1%(%( lY__pycache__/char.cpython-311.pycnu刐迭PK!xΙ!!$醽__pycache__/namedval.cpython-311.pycnu刐迭PK!4:II"F__pycache__/tagmap.cpython-311.pycnu刐迭PK!馼軟## 岽namedval.pynu刐迭PK!珥"V"V?base.pynu刐迭PK!c縳┺$$char.pynu刐迭PK!鹡{c湭湭瑿univ.pynu刐迭PK!鎴波 useful.pynu刐迭PK!D@匯;; ]__init__.pynu刐迭PK!f3?3? namedtype.pynu刐迭PK!%%BCtag.pynu刐迭PKAA慼