desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Create a copy of a |ASN.1| type or object. Any parameters to the *subtype()* method will be added to the corresponding properties of the |ASN.1| object. Parameters value: :class:`tuple`, :class:`float` or |ASN.1| object Initialization value to pass to new ASN.1 object instead of inheriting one from the caller. implici...
def subtype(self, value=noValue, implicitTag=None, explicitTag=None, subtypeSpec=None):
return base.AbstractSimpleAsn1Item.subtype(self, value, implicitTag, explicitTag)
'Indicate PLUS-INFINITY object value Returns : :class:`bool` :class:`True` if calling object represents plus infinity or :class:`False` otherwise.'
def isPlusInfinity(self):
return (self._value == self._plusInf)
'Indicate MINUS-INFINITY object value Returns : :class:`bool` :class:`True` if calling object represents minus infinity or :class:`False` otherwise.'
def isMinusInfinity(self):
return (self._value == self._minusInf)
'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 (of *componentType is set). In the latter case a new component type gets instanti...
def getComponentByPosition(self, idx):
try: return self._componentValues[idx] except IndexError: self.setComponentByPosition(idx) return self._componentValues[idx]
'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 i...
def setComponentByPosition(self, idx, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True):
componentType = self._componentType try: currentValue = self._componentValues[idx] except IndexError: currentValue = None if (len(self._componentValues) < idx): raise error.PyAsn1Error('Component index out of range') if ((value is None) or (value is noValu...
'Indicate if |ASN.1| object components represent ASN.1 type or ASN.1 value. The PyASN1 type objects can only participate in types comparison and serve as a blueprint for serialization codecs to resolve ambiguous types. The PyASN1 value objects can additionally participate in most of built-in Python operations. Returns ...
@property def isValue(self):
if (not self._componentValues): return False for componentValue in self._componentValues: if (not componentValue.isValue): return False return 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 Returns : :py:class:`~pyasn1.type.base.PyAsn1Item` Instantiate |ASN.1| component type or return existing component value'
def getComponentByName(self, name):
return self.getComponentByPosition(self._componentType.getPositionByName(name))
'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 value : :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentTyp...
def setComponentByName(self, name, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True):
return self.setComponentByPosition(self._componentType.getPositionByName(name), value, verifyConstraints, matchTags, matchConstraints)
'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 type object gets instantiated. Returns : :py:class:`~pyasn1.type.bas...
def getComponentByPosition(self, idx):
try: componentValue = self._componentValues[idx] except IndexError: componentValue = None if (componentValue is None): self.setComponentByPosition(idx) return self._componentValues[idx]
'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....
def setComponentByPosition(self, idx, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True):
componentType = self._componentType componentTypeLen = self._componentTypeLen try: currentValue = self._componentValues[idx] except IndexError: currentValue = None if componentTypeLen: if (componentTypeLen < idx): raise IndexError('component index ...
'Indicate if |ASN.1| object components represent ASN.1 type or ASN.1 value. The PyASN1 type objects can only participate in types comparison and serve as a blueprint for serialization codecs to resolve ambiguous types. The PyASN1 value objects can additionally participate in most of built-in Python operations. Returns ...
@property def isValue(self):
componentType = self._componentType if componentType: for (idx, subComponentType) in enumerate(componentType.namedTypes): if (subComponentType.isDefaulted or subComponentType.isOptional): continue if ((not self._componentValues) or (self._componentValues[idx] is N...
'Return an object representation string. Returns : :class:`str` Human-friendly object representation.'
def prettyPrint(self, scope=0):
scope += 1 representation = (self.__class__.__name__ + ':\n') for idx in range(len(self._componentValues)): if (self._componentValues[idx] is not None): representation += (' ' * scope) componentType = self.getComponentType() if (componentType is None): ...
'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 Returns : :py:class:`~pyasn1.type.base.PyAsn1Item` a pyasn1 object'
def getComponentByType(self, tagSet, innerFlag=False):
component = self.getComponentByPosition(self._componentType.getPositionByType(tagSet)) if (innerFlag and isinstance(component, Set)): return component.getComponent(innerFlag=True) else: return component
'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 value : :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componen...
def setComponentByType(self, tagSet, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True, innerFlag=False):
idx = self._componentType.getPositionByType(tagSet) if innerFlag: componentType = self._componentType.getTypeByPosition(idx) if componentType.tagSet: return self.setComponentByPosition(idx, value, verifyConstraints, matchTags, matchConstraints) else: componentType...
'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, o...
def setComponentByPosition(self, idx, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True):
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] = None return self
'Return a :class:`~pyasn1.type.tag.TagSet` object of the currently initialized component or self (if |ASN.1| is tagged).'
@property def effectiveTagSet(self):
if self._tagSet: return self._tagSet else: component = self.getComponent() return component.effectiveTagSet
'"Return a :class:`~pyasn1.type.tagmap.TagMap` object mapping ASN.1 tags to ASN.1 objects contained within callee.'
@property def tagMap(self):
if self._tagSet: return Set.tagMap.fget(self) else: return Set.componentTagMap.fget(self)
'Return currently assigned component of the |ASN.1| object. Returns : :py:class:`~pyasn1.type.base.PyAsn1Item` a PyASN1 object'
def getComponent(self, innerFlag=0):
if (self._currentIdx is None): raise error.PyAsn1Error('Component not chosen') else: c = self._componentValues[self._currentIdx] if (innerFlag and isinstance(c, Choice)): return c.getComponent(innerFlag) else: return c
'Return the name of currently assigned component of the |ASN.1| object. Returns : :py:class:`str` |ASN.1| component name'
def getName(self, innerFlag=False):
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(...
'Indicate if |ASN.1| component is set and represents ASN.1 type or ASN.1 value. The PyASN1 type objects can only participate in types comparison and serve as a blueprint for serialization codecs to resolve ambiguous types. The PyASN1 value objects can additionally participate in most of built-in Python operations. Retu...
@property def isValue(self):
if (self._currentIdx is None): return False return self._componentValues[self._currentIdx].isValue
'"Return a :class:`~pyasn1.type.tagmap.TagMap` object mapping ASN.1 tags to ASN.1 objects contained within callee.'
@property def tagMap(self):
try: return self._tagMap except AttributeError: self._tagMap = tagmap.TagMap({self.tagSet: self}, {eoo.endOfOctets.tagSet: eoo.endOfOctets}, self) return self._tagMap
'Creates a copy of a |ASN.1| type or object. Any parameters to the *clone()* method will replace corresponding properties of the |ASN.1| object. Parameters value: :class:`unicode`, :class:`str`, :class:`bytes` or |ASN.1| object unicode object (Python 2) or string (Python 3), alternatively string (Python 2) or bytes (Py...
def clone(self, value=noValue, tagSet=None, subtypeSpec=None, encoding=None, binValue=noValue, hexValue=noValue):
return univ.OctetString.clone(self, value, tagSet, subtypeSpec, encoding, binValue, hexValue)
'Creates a copy of a |ASN.1| type or object. Any parameters to the *subtype()* method will be added to the corresponding properties of the |ASN.1| object. Parameters value: :class:`unicode`, :class:`str`, :class:`bytes` or |ASN.1| object unicode object (Python 2) or string (Python 3), alternatively string (Python 2) or...
def subtype(self, value=noValue, implicitTag=None, explicitTag=None, subtypeSpec=None, encoding=None, binValue=noValue, hexValue=noValue):
return univ.OctetString.subtype(self, value, implicitTag, explicitTag, subtypeSpec, encoding, binValue, hexValue)
'Return ASN.1 type object by its position in fields set. Parameters idx: :py:class:`int` Field index Returns ASN.1 type Raises : :class:`~pyasn1.error.PyAsn1Error` If given position is out of fields range'
def getTypeByPosition(self, idx):
try: return self.__namedTypes[idx].asn1Object except IndexError: raise error.PyAsn1Error('Type position out of range')
'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 : :class:`~pyasn1.error.PyAsn1Error` If *tagSet* is not present or ASN.1 types are not unique within c...
def getPositionByType(self, tagSet):
try: return self.__tagToPosMap[tagSet] except KeyError: raise error.PyAsn1Error(('Type %s not found' % (tagSet,)))
'Return field name by its position in fields set. Parameters idx: :py:class:`idx` Field index Returns : :py:class:`str` Field name Raises : :class:`~pyasn1.error.PyAsn1Error` If given field name is not present in callee *NamedTypes*'
def getNameByPosition(self, idx):
try: return self.__namedTypes[idx].name except IndexError: raise error.PyAsn1Error('Type position out of range')
'Return field position by filed name. Parameters name: :py:class:`str` Field name Returns : :py:class:`int` Field position in fields set Raises : :class:`~pyasn1.error.PyAsn1Error` If *name* is not present or not unique within callee *NamedTypes*'
def getPositionByName(self, name):
try: return self.__nameToPosMap[name] except KeyError: raise error.PyAsn1Error(('Name %s not found' % (name,)))
'Return ASN.1 types that are allowed at or past given field position. Some ASN.1 serialization 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...
def getTagMapNearPosition(self, idx):
try: return self.__ambigiousTypes[idx].getTagMap() except KeyError: raise error.PyAsn1Error('Type position out of range')
'Return the closest field position where given ASN.1 type is allowed. Some ASN.1 serialization 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 ...
def getPositionNearType(self, tagSet, idx):
try: return (idx + self.__ambigiousTypes[idx].getPositionByType(tagSet)) except KeyError: raise error.PyAsn1Error('Type position out of range')
'Return the minimal TagSet among ASN.1 type in callee *NamedTypes*. Some ASN.1 types/serialization 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*...
@property def minTagSet(self):
if (self.__minTagSet is None): for namedType in self.__namedTypes: asn1Object = namedType.asn1Object try: tagSet = asn1Object.getMinTagSet() except AttributeError: tagSet = asn1Object.tagSet if ((self.__minTagSet is None) or (ta...
'Create a *TagMap* object from tags and types recursively. Create a new :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 *.getTagMap()...
def getTagMap(self, unique=False):
if (unique not in self.__tagMap): presentTypes = {} skipTypes = {} defaultType = None for namedType in self.__namedTypes: tagMap = namedType.asn1Object.tagMap for tagSet in tagMap: if (unique and (tagSet in presentTypes)): r...
'Build the wrapper'
def __init__(self, library):
self._lib = ctypes.CDLL(library) (self._version, self._hexversion, self._cflags) = get_version(self._lib) self._libreSSL = self._version.startswith('LibreSSL') self.pointer = ctypes.pointer self.c_int = ctypes.c_int self.byref = ctypes.byref self.create_string_buffer = ctypes.create_string_b...
'returns the length of a BN (OpenSSl API)'
def BN_num_bytes(self, x):
return int(((self.BN_num_bits(x) + 7) / 8))
'returns the OpenSSL cipher instance'
def get_cipher(self, name):
if (name not in self.cipher_algo): raise Exception('Unknown cipher') return self.cipher_algo[name]
'returns the id of a elliptic curve'
def get_curve(self, name):
if (name not in self.curves): raise Exception('Unknown curve') return self.curves[name]
'returns the name of a elliptic curve with his id'
def get_curve_by_id(self, id):
res = None for i in self.curves: if (self.curves[i] == id): res = i break if (res is None): raise Exception('Unknown curve') return res
'OpenSSL random function'
def rand(self, size):
buffer = self.malloc(0, size) while (self.RAND_bytes(buffer, size) != 1): import time time.sleep(1) return buffer.raw
'returns a create_string_buffer (ctypes)'
def malloc(self, data, size):
buffer = None if (data != 0): if ((sys.version_info.major == 3) and isinstance(data, type(''))): data = data.encode() buffer = self.create_string_buffer(data, size) else: buffer = self.create_string_buffer(size) return buffer
'For a normal and High level use, specifie pubkey, privkey (if you need) and the curve'
def __init__(self, pubkey=None, privkey=None, pubkey_x=None, pubkey_y=None, raw_privkey=None, curve='sect283r1'):
if (type(curve) == str): self.curve = OpenSSL.get_curve(curve) else: self.curve = curve if ((pubkey_x is not None) and (pubkey_y is not None)): self._set_keys(pubkey_x, pubkey_y, raw_privkey) elif (pubkey is not None): (curve, pubkey_x, pubkey_y, i) = ECC._decode_pubkey(p...
'static method, returns the list of all the curves available'
@staticmethod def get_curves():
return OpenSSL.curves.keys()
'High level function which returns : curve(2) + len_of_pubkeyX(2) + pubkeyX + len_of_pubkeyY + pubkeyY'
def get_pubkey(self):
return ''.join((pack('!H', self.curve), pack('!H', len(self.pubkey_x)), self.pubkey_x, pack('!H', len(self.pubkey_y)), self.pubkey_y))
'High level function which returns curve(2) + len_of_privkey(2) + privkey'
def get_privkey(self):
return ''.join((pack('!H', self.curve), pack('!H', len(self.privkey)), self.privkey))
'High level function. Compute public key with the local private key and returns a 512bits shared key'
def get_ecdh_key(self, pubkey):
(curve, pubkey_x, pubkey_y, i) = ECC._decode_pubkey(pubkey) if (curve != self.curve): raise Exception('ECC keys must be from the same curve !') return sha512(self.raw_get_ecdh_key(pubkey_x, pubkey_y)).digest()
'Check the public key and the private key. The private key is optional (replace by None)'
def check_key(self, privkey, pubkey):
(curve, pubkey_x, pubkey_y, i) = ECC._decode_pubkey(pubkey) if (privkey is None): raw_privkey = None curve2 = curve else: (curve2, raw_privkey, i) = ECC._decode_privkey(privkey) if (curve != curve2): raise Exception('Bad public and private key') return sel...
'Sign the input with ECDSA method and returns the signature'
def sign(self, inputb, digest_alg=OpenSSL.digest_ecdsa_sha1):
try: size = len(inputb) buff = OpenSSL.malloc(inputb, size) digest = OpenSSL.malloc(0, 64) if ((OpenSSL._hexversion > 269484032) and (not OpenSSL._libreSSL)): md_ctx = OpenSSL.EVP_MD_CTX_new() else: md_ctx = OpenSSL.EVP_MD_CTX_create() dgst_len...
'Verify the signature with the input and the local public key. Returns a boolean'
def verify(self, sig, inputb, digest_alg=OpenSSL.digest_ecdsa_sha1):
try: bsig = OpenSSL.malloc(sig, len(sig)) binputb = OpenSSL.malloc(inputb, len(inputb)) digest = OpenSSL.malloc(0, 64) dgst_len = OpenSSL.pointer(OpenSSL.c_int(0)) if ((OpenSSL._hexversion > 269484032) and (not OpenSSL._libreSSL)): md_ctx = OpenSSL.EVP_MD_CTX_new(...
'Encrypt data with ECIES method using the public key of the recipient.'
@staticmethod def encrypt(data, pubkey, ephemcurve=None, ciphername='aes-256-cbc'):
(curve, pubkey_x, pubkey_y, i) = ECC._decode_pubkey(pubkey) return ECC.raw_encrypt(data, pubkey_x, pubkey_y, curve=curve, ephemcurve=ephemcurve, ciphername=ciphername)
'Decrypt data with ECIES method using the local private key'
def decrypt(self, data, ciphername='aes-256-cbc'):
blocksize = OpenSSL.get_cipher(ciphername).get_blocksize() iv = data[:blocksize] i = blocksize (curve, pubkey_x, pubkey_y, i2) = ECC._decode_pubkey(data[i:]) i += i2 ciphertext = data[i:(len(data) - 32)] i += len(ciphertext) mac = data[i:] key = sha512(self.raw_get_ecdh_key(pubkey_x,...
'do == 1 => Encrypt; do == 0 => Decrypt'
def __init__(self, key, iv, do, ciphername='aes-256-cbc'):
self.cipher = OpenSSL.get_cipher(ciphername) self.ctx = OpenSSL.EVP_CIPHER_CTX_new() if ((do == 1) or (do == 0)): k = OpenSSL.malloc(key, len(key)) IV = OpenSSL.malloc(iv, len(iv)) OpenSSL.EVP_CipherInit_ex(self.ctx, self.cipher.get_pointer(), 0, k, IV, do) else: raise Ex...
'static method, returns all ciphers available'
@staticmethod def get_all_cipher():
return OpenSSL.cipher_algo.keys()
'Do update and final in one method'
def ciphering(self, input):
buff = self.update(input) return (buff + self.final())
'Internal method used to convert the utf-8 encoded bytestring into unicode. If the conversion fails, the socket will be closed.'
def _decode_bytes(self, bytestring):
if (not bytestring): return '' try: return bytestring.decode('utf-8') except UnicodeDecodeError: self.close(1007) raise
':returns: The utf-8 byte string equivalent of `text`.'
def _encode_bytes(self, text):
if (not isinstance(text, str)): text = text_type((text or '')) return text.encode('utf-8')
':returns: Whether the returned close code is a valid hybi return code.'
def _is_valid_close_code(self, code):
if (code < 1000): return False if (1004 <= code <= 1006): return False if (1012 <= code <= 1016): return False if (code == 1100): return False if (2000 <= code <= 2999): return False return True
'Called when a close frame has been decoded from the stream. :param header: The decoded `Header`. :param payload: The bytestring payload associated with the close frame.'
def handle_close(self, header, payload):
if (not payload): self.close(1000, None) return if (len(payload) < 2): raise ProtocolError('Invalid close frame: {0} {1}'.format(header, payload)) code = struct.unpack('!H', payload[:2])[0] payload = payload[2:] if payload: validator = Utf8Validator() ...
'Block until a full frame has been read from the socket. This is an internal method as calling this will not cleanup correctly if an exception is called. Use `receive` instead. :return: The header and payload as a tuple.'
def read_frame(self):
header = Header.decode_header(self.stream) if header.flags: raise ProtocolError if (not header.length): return (header, '') try: payload = self.raw_read(header.length) except socket.error: payload = '' except Exception: payload = '' if (len(payload) !=...
'Return the next text or binary message from the socket. This is an internal method as calling this will not cleanup correctly if an exception is called. Use `receive` instead.'
def read_message(self):
opcode = None message = bytearray() while True: (header, payload) = self.read_frame() f_opcode = header.opcode if (f_opcode in (self.OPCODE_TEXT, self.OPCODE_BINARY)): if opcode: raise ProtocolError('The opcode in non-fin frame is expecte...
'Read and return a message from the stream. If `None` is returned, then the socket is considered closed/errored.'
def receive(self):
if self.closed: self.current_app.on_close(MSG_ALREADY_CLOSED) raise WebSocketError(MSG_ALREADY_CLOSED) try: return self.read_message() except UnicodeError: self.close(1007) except ProtocolError: self.close(1002) except socket.timeout: self.close() ...
'Send a frame over the websocket with message as its payload'
def send_frame(self, message, opcode):
if self.closed: self.current_app.on_close(MSG_ALREADY_CLOSED) raise WebSocketError(MSG_ALREADY_CLOSED) if (not message): return if (opcode in (self.OPCODE_TEXT, self.OPCODE_PING)): message = self._encode_bytes(message) elif (opcode == self.OPCODE_BINARY): message ...
'Send a frame over the websocket with message as its payload'
def send(self, message, binary=None):
if (binary is None): binary = (not isinstance(message, string_types)) opcode = (self.OPCODE_BINARY if binary else self.OPCODE_TEXT) try: self.send_frame(message, opcode) except WebSocketError: self.current_app.on_close(MSG_SOCKET_DEAD) raise WebSocketError(MSG_SOCKET_DEAD...
'Close the websocket and connection, sending the specified code and message. The underlying socket object is _not_ closed, that is the responsibility of the initiator.'
def close(self, code=1000, message=''):
if self.closed: self.current_app.on_close(MSG_ALREADY_CLOSED) try: message = self._encode_bytes(message) self.send_frame(message, opcode=self.OPCODE_CLOSE) except WebSocketError: self.logger.debug('Failed to write closing frame -> closing socket') fin...
'Decode a WebSocket header. :param stream: A file like object that can be \'read\' from. :returns: A `Header` instance.'
@classmethod def decode_header(cls, stream):
read = stream.read data = read(2) if (len(data) != 2): raise WebSocketError('Unexpected EOF while decoding header') (first_byte, second_byte) = struct.unpack('!BB', data) header = cls(fin=((first_byte & cls.FIN_MASK) == cls.FIN_MASK), opcode=(first_byte & cls.OPCODE_MASK), flags=...
'Encodes a WebSocket header. :param fin: Whether this is the final frame for this opcode. :param opcode: The opcode of the payload, see `OPCODE_*` :param mask: Whether the payload is masked. :param length: The length of the frame. :param flags: The RSV* flags. :return: A bytestring encoded header.'
@classmethod def encode_header(cls, fin, opcode, mask, length, flags):
first_byte = opcode second_byte = 0 extra = '' result = bytearray() if fin: first_byte |= cls.FIN_MASK if (flags & cls.RSV0_MASK): first_byte |= cls.RSV0_MASK if (flags & cls.RSV1_MASK): first_byte |= cls.RSV1_MASK if (flags & cls.RSV2_MASK): first_byte |=...
'Called when a websocket has been created successfully.'
def run_websocket(self):
if getattr(self, 'prevent_wsgi_call', False): return if (not hasattr(self.server, 'clients')): self.server.clients = {} try: self.server.clients[self.client_address] = Client(self.client_address, self.websocket) list(self.application(self.environ, (lambda s, h, e=None: []))) ...
'Attempt to upgrade the current environ into a websocket enabled connection. If successful, the environ dict with be updated with two new entries, `wsgi.websocket` and `wsgi.websocket_version`. :returns: Whether the upgrade was successful.'
def upgrade_websocket(self):
self.logger.debug('Validating WebSocket request') if (self.environ.get('REQUEST_METHOD', '') != 'GET'): self.logger.debug('Can only upgrade connection if using GET method.') return upgrade = self.environ.get('HTTP_UPGRADE', '').lower() if (upgrade == 'websocket...
'Validate and \'upgrade\' the HTTP request to a WebSocket request. If an upgrade succeeded then then handler will have `start_response` with a status of `101`, the environ will also be updated with `wsgi.websocket` and `wsgi.websocket_version` keys. :param environ: The WSGI environ dict. :param start_response: The call...
def upgrade_connection(self):
self.logger.debug('Attempting to upgrade connection') version = self.environ.get('HTTP_SEC_WEBSOCKET_VERSION') if (version not in self.SUPPORTED_VERSIONS): msg = 'Unsupported WebSocket Version: {0}'.format(version) self.logger.warning(msg) self.start_response('400 ...
'Called when the handler is ready to send a response back to the remote endpoint. A websocket connection may have not been created.'
def start_response(self, status, headers, exc_info=None):
writer = super(WebSocketHandler, self).start_response(status, headers, exc_info=exc_info) self._prepare_response() return writer
'Sets up the ``pywsgi.Handler`` to work with a websocket response. This is used by other projects that need to support WebSocket connections as part of a larger effort.'
def _prepare_response(self):
assert (not self.headers_sent) if (not self.environ.get('wsgi.websocket')): return self.provided_content_length = False self.response_use_chunked = False self.close_connection = True self.provided_date = True
'I haven\'t seen this action type be sent from a tracker, but I\'ve left it here for the possibility.'
def _process_error(self, payload, trans):
self.error(payload) return payload
'http://www.bittorrent.org/beps/bep_0020.html'
def _generate_peer_id(self):
peer_id = (('-PU' + __version__.replace('.', '-')) + '-') remaining = (20 - len(peer_id)) numbers = [str(random.randint(0, 9)) for _ in xrange(remaining)] peer_id += ''.join(numbers) assert (len(peer_id) == 20) return peer_id
'update(arg)'
def update(self, arg):
RMD160Update(self.ctx, arg, len(arg)) self.dig = None
'digest()'
def digest(self):
if self.dig: return self.dig ctx = self.ctx.copy() self.dig = RMD160Final(self.ctx) self.ctx = ctx return self.dig
'hexdigest()'
def hexdigest(self):
dig = self.digest() hex_digest = '' for d in dig: if is_python2: hex_digest += ('%02x' % ord(d)) else: hex_digest += ('%02x' % d) return hex_digest
'copy()'
def copy(self):
import copy return copy.deepcopy(self)
'Batch RPC call. Pass array of arrays: [ [ "method", params... ], ... ] Returns array of results.'
def batch_(self, rpc_calls):
batch_data = [] for rpc_call in rpc_calls: AuthServiceProxy.__id_count += 1 m = rpc_call.pop(0) batch_data.append({'jsonrpc': '2.0', 'method': m, 'params': rpc_call, 'id': AuthServiceProxy.__id_count}) postdata = json.dumps(batch_data, default=EncodeDecimal) log.debug(('--> ' ...
'Return the longhand version of the IP address as a string.'
@property def exploded(self):
return self._explode_shorthand_ip_string()
'Return the shorthand version of the IP address as a string.'
@property def compressed(self):
return str(self)
'Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn\'t return the network or broadcast addresses.'
def iterhosts(self):
cur = (int(self.network) + 1) bcast = (int(self.broadcast) - 1) while (cur <= bcast): cur += 1 (yield IPAddress((cur - 1), version=self._version))
'Tell if self is partly contained in other.'
def overlaps(self, other):
return ((self.network in other) or (self.broadcast in other) or ((other.network in self) or (other.broadcast in self)))
'Number of hosts in the current subnet.'
@property def numhosts(self):
return ((int(self.broadcast) - int(self.network)) + 1)
'Remove an address from a larger block. For example: addr1 = IPNetwork(\'10.1.1.0/24\') addr2 = IPNetwork(\'10.1.1.0/26\') addr1.address_exclude(addr2) = [IPNetwork(\'10.1.1.64/26\'), IPNetwork(\'10.1.1.128/25\')] or IPv6: addr1 = IPNetwork(\'::1/32\') addr2 = IPNetwork(\'::1/128\') addr1.address_exclude(addr2) = [IPNe...
def address_exclude(self, other):
if (not (self._version == other._version)): raise TypeError(('%s and %s are not of the same version' % (str(self), str(other)))) if (not isinstance(other, _BaseNet)): raise TypeError(('%s is not a network object' % str(other))) if (other not in self): ...
'Compare two IP objects. This is only concerned about the comparison of the integer representation of the network addresses. This means that the host bits aren\'t considered at all in this method. If you want to compare host bits, you can easily enough do a \'HostA._ip < HostB._ip\' Args: other: An IP object. Returns...
def compare_networks(self, other):
if (self._version < other._version): return (-1) if (self._version > other._version): return 1 if (self.network < other.network): return (-1) if (self.network > other.network): return 1 if (self.netmask < other.netmask): return (-1) if (self.netmask > othe...
'Network-only key function. Returns an object that identifies this address\' network and netmask. This function is a suitable "key" argument for sorted() and list.sort().'
def _get_networks_key(self):
return (self._version, self.network, self.netmask)
'Turn the prefix length netmask into a int for comparison. Args: prefixlen: An integer, the prefix length. Returns: An integer.'
def _ip_int_from_prefix(self, prefixlen=None):
if ((not prefixlen) and (prefixlen != 0)): prefixlen = self._prefixlen return (self._ALL_ONES ^ (self._ALL_ONES >> prefixlen))
'Return prefix length from the decimal netmask. Args: ip_int: An integer, the IP address. mask: The netmask. Defaults to 32. Returns: An integer, the prefix length.'
def _prefix_from_ip_int(self, ip_int, mask=32):
while mask: if ((ip_int & 1) == 1): break ip_int >>= 1 mask -= 1 return mask
'Turn a prefix length into a dotted decimal string. Args: prefixlen: An integer, the netmask prefix length. Returns: A string, the dotted decimal netmask string.'
def _ip_string_from_prefix(self, prefixlen=None):
if (not prefixlen): prefixlen = self._prefixlen return self._string_from_ip_int(self._ip_int_from_prefix(prefixlen))
'The subnets which join to make the current subnet. In the case that self contains only one IP (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 for IPv6), return a list with just ourself. Args: prefixlen_diff: An integer, the amount the prefix length should be increased by. This should not be set if new_prefix...
def iter_subnets(self, prefixlen_diff=1, new_prefix=None):
if (self._prefixlen == self._max_prefixlen): (yield self) return if (new_prefix is not None): if (new_prefix < self._prefixlen): raise ValueError('new prefix must be longer') if (prefixlen_diff != 1): raise ValueError('cannot set prefixle...
'Return the network object with the host bits masked out.'
def masked(self):
return IPNetwork(('%s/%d' % (self.network, self._prefixlen)), version=self._version)
'Return a list of subnets, rather than an iterator.'
def subnet(self, prefixlen_diff=1, new_prefix=None):
return list(self.iter_subnets(prefixlen_diff, new_prefix))
'The supernet containing the current network. Args: prefixlen_diff: An integer, the amount the prefix length of the network should be decreased by. For example, given a /24 network and a prefixlen_diff of 3, a supernet with a /21 netmask is returned. Returns: An IPv4 network object. Raises: ValueError: If self.prefixl...
def supernet(self, prefixlen_diff=1, new_prefix=None):
if (self._prefixlen == 0): return self if (new_prefix is not None): if (new_prefix > self._prefixlen): raise ValueError('new prefix must be shorter') if (prefixlen_diff != 1): raise ValueError('cannot set prefixlen_diff and new_prefix') ...
'Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn\'t a valid IPv4 Address.'
def _ip_int_from_string(self, ip_str):
octets = ip_str.split('.') if (len(octets) != 4): raise AddressValueError(ip_str) packed_ip = 0 for oc in octets: try: packed_ip = ((packed_ip << 8) | self._parse_octet(oc)) except ValueError: raise AddressValueError(ip_str) return packed_ip
'Convert a decimal octet into an integer. Args: octet_str: A string, the number to parse. Returns: The octet as an integer. Raises: ValueError: if the octet isn\'t strictly a decimal from [0..255].'
def _parse_octet(self, octet_str):
if (not self._DECIMAL_DIGITS.issuperset(octet_str)): raise ValueError octet_int = int(octet_str, 10) if ((octet_int > 255) or ((octet_str[0] == '0') and (len(octet_str) > 1))): raise ValueError return octet_int
'Turns a 32-bit integer into dotted decimal notation. Args: ip_int: An integer, the IP address. Returns: The IP address as a string in dotted decimal notation.'
def _string_from_ip_int(self, ip_int):
octets = [] for _ in xrange(4): octets.insert(0, str((ip_int & 255))) ip_int >>= 8 return '.'.join(octets)
'The binary representation of this address.'
@property def packed(self):
return v4_int_to_packed(self._ip)
'Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within the reserved IPv4 Network range.'
@property def is_reserved(self):
return (self in IPv4Network('240.0.0.0/4'))
'Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per RFC 1918.'
@property def is_private(self):
return ((self in IPv4Network('10.0.0.0/8')) or (self in IPv4Network('172.16.0.0/12')) or (self in IPv4Network('192.168.0.0/16')))
'Test if the address is reserved for multicast use. Returns: A boolean, True if the address is multicast. See RFC 3171 for details.'
@property def is_multicast(self):
return (self in IPv4Network('224.0.0.0/4'))
'Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 5735 3.'
@property def is_unspecified(self):
return (self in IPv4Network('0.0.0.0'))
'Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback per RFC 3330.'
@property def is_loopback(self):
return (self in IPv4Network('127.0.0.0/8'))
'Test if the address is reserved for link-local. Returns: A boolean, True if the address is link-local per RFC 3927.'
@property def is_link_local(self):
return (self in IPv4Network('169.254.0.0/16'))