desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Delete train log. Parameters args : dictionary, find items to delete, leave it empty to delete all log.'
@AutoFill def del_train_log(self, args={}):
self.db.TrainLog.delete_many(args) print '[TensorDB] Delete TrainLog SUCCESS'
'Save the validating log. Parameters args : dictionary, items to save. Examples >>> db.valid_log(time=time.time(), {\'loss\': loss, \'acc\': acc})'
@AutoFill def valid_log(self, args={}):
_result = self.db.ValidLog.insert_one(args) _log = self._print_dict(args) print ('[TensorDB] ValidLog: ' + _log) return _result
'Delete validation log. Parameters args : dictionary, find items to delete, leave it empty to delete all log.'
@AutoFill def del_valid_log(self, args={}):
self.db.ValidLog.delete_many(args) print '[TensorDB] Delete ValidLog SUCCESS'
'Save the testing log. Parameters args : dictionary, items to save. Examples >>> db.test_log(time=time.time(), {\'loss\': loss, \'acc\': acc})'
@AutoFill def test_log(self, args={}):
_result = self.db.TestLog.insert_one(args) _log = self._print_dict(args) print ('[TensorDB] TestLog: ' + _log) return _result
'Delete test log. Parameters args : dictionary, find items to delete, leave it empty to delete all log.'
@AutoFill def del_test_log(self, args={}):
self.db.TestLog.delete_many(args) print '[TensorDB] Delete TestLog SUCCESS'
'Save the job. Parameters script : a script file name or None. args : dictionary, items to save. Examples >>> # Save your job >>> db.save_job(\'your_script.py\', {\'job_id\': 1, \'learning_rate\': 0.01, \'n_units\': 100}) >>> # Run your job >>> temp = db.find_one_job(args={\'job_id\': 1}) >>> print(temp[\'learning_rate\']) ... 0.01 >>> import _your_script ... running your script'
@AutoFill def save_job(self, script=None, args={}):
self.__autofill(args) if (script is not None): _script = open(script, 'rb').read() args.update({'script': _script, 'script_name': script}) _result = self.db.Job.replace_one(args, args, upsert=True) _log = self._print_dict(args) print '[TensorDB] Save Job: script={}, args={}'.format(script, args) return _result
'Find one job from MongoDB Job Collections. Parameters args : dictionary, find items. Returns dictionary : contains all meta data and script.'
@AutoFill def find_one_job(self, args={}):
temp = self.db.Job.find_one(args) if (temp is not None): if ('script_name' in temp.keys()): f = open(('_' + temp['script_name']), 'wb') f.write(temp['script']) f.close() print '[TensorDB] Find Job: {}'.format(args) else: print '[TensorDB] FAIL! Cannot find any: {}'.format(args) return False return temp
'Print all info of parameters in the network'
def print_params(self, details=True):
for (i, p) in enumerate(self.all_params): if details: try: val = p.eval() print ' param {:3}: {:20} {:15} {} (mean: {:<18}, median: {:<18}, std: {:<18}) '.format(i, p.name, str(val.shape), p.dtype.name, val.mean(), np.median(val), val.std()) except Exception as e: print str(e) raise Exception('Hint: print params details after tl.layers.initialize_global_variables(sess) or use network.print_params(False).') else: print ' param {:3}: {:20} {:15} {}'.format(i, p.name, str(p.get_shape()), p.dtype.name) print (' num of params: %d' % self.count_params())
'Print all info of layers in the network'
def print_layers(self):
for (i, layer) in enumerate(self.all_layers): print ' layer {:3}: {:20} {:15} {}'.format(i, layer.name, str(layer.get_shape()), layer.dtype.name)
'Return the number of parameters in the network'
def count_params(self):
n_params = 0 for (i, p) in enumerate(self.all_params): n = 1 for s in p.get_shape(): try: s = int(s) except: s = 1 if s: n = (n * s) n_params = (n_params + n) return n_params
'Run a step of the model feeding the given inputs. Parameters session : tensorflow session to use. encoder_inputs : list of numpy int vectors to feed as encoder inputs. decoder_inputs : list of numpy int vectors to feed as decoder inputs. target_weights : list of numpy float vectors to feed as target weights. bucket_id : which bucket of the model to use. forward_only : whether to do the backward step or only forward. Returns A triple consisting of gradient norm (or None if we did not do backward), average perplexity, and the outputs. Raises ValueError : if length of encoder_inputs, decoder_inputs, or target_weights disagrees with bucket size for the specified bucket_id.'
def step(self, session, encoder_inputs, decoder_inputs, target_weights, bucket_id, forward_only):
(encoder_size, decoder_size) = self.buckets[bucket_id] if (len(encoder_inputs) != encoder_size): raise ValueError(('Encoder length must be equal to the one in bucket, %d != %d.' % (len(encoder_inputs), encoder_size))) if (len(decoder_inputs) != decoder_size): raise ValueError(('Decoder length must be equal to the one in bucket, %d != %d.' % (len(decoder_inputs), decoder_size))) if (len(target_weights) != decoder_size): raise ValueError(('Weights length must be equal to the one in bucket, %d != %d.' % (len(target_weights), decoder_size))) input_feed = {} for l in xrange(encoder_size): input_feed[self.encoder_inputs[l].name] = encoder_inputs[l] for l in xrange(decoder_size): input_feed[self.decoder_inputs[l].name] = decoder_inputs[l] input_feed[self.target_weights[l].name] = target_weights[l] last_target = self.decoder_inputs[decoder_size].name input_feed[last_target] = np.zeros([self.batch_size], dtype=np.int32) if (not forward_only): output_feed = [self.updates[bucket_id], self.gradient_norms[bucket_id], self.losses[bucket_id]] else: output_feed = [self.losses[bucket_id]] for l in xrange(decoder_size): output_feed.append(self.outputs[bucket_id][l]) outputs = session.run(output_feed, input_feed) if (not forward_only): return (outputs[1], outputs[2], None) else: return (None, outputs[0], outputs[1:])
'Get a random batch of data from the specified bucket, prepare for step. To feed data in step(..) it must be a list of batch-major vectors, while data here contains single length-major cases. So the main logic of this function is to re-index data cases to be in the proper format for feeding. Parameters data : a tuple of size len(self.buckets) in which each element contains lists of pairs of input and output data that we use to create a batch. bucket_id : integer, which bucket to get the batch for. PAD_ID : int Index of Padding in vocabulary GO_ID : int Index of GO in vocabulary EOS_ID : int Index of End of sentence in vocabulary UNK_ID : int Index of Unknown word in vocabulary Returns The triple (encoder_inputs, decoder_inputs, target_weights) for the constructed batch that has the proper format to call step(...) later.'
def get_batch(self, data, bucket_id, PAD_ID=0, GO_ID=1, EOS_ID=2, UNK_ID=3):
(encoder_size, decoder_size) = self.buckets[bucket_id] (encoder_inputs, decoder_inputs) = ([], []) for _ in xrange(self.batch_size): (encoder_input, decoder_input) = random.choice(data[bucket_id]) encoder_pad = ([PAD_ID] * (encoder_size - len(encoder_input))) encoder_inputs.append(list(reversed((encoder_input + encoder_pad)))) decoder_pad_size = ((decoder_size - len(decoder_input)) - 1) decoder_inputs.append((([GO_ID] + decoder_input) + ([PAD_ID] * decoder_pad_size))) (batch_encoder_inputs, batch_decoder_inputs, batch_weights) = ([], [], []) for length_idx in xrange(encoder_size): batch_encoder_inputs.append(np.array([encoder_inputs[batch_idx][length_idx] for batch_idx in xrange(self.batch_size)], dtype=np.int32)) for length_idx in xrange(decoder_size): batch_decoder_inputs.append(np.array([decoder_inputs[batch_idx][length_idx] for batch_idx in xrange(self.batch_size)], dtype=np.int32)) batch_weight = np.ones(self.batch_size, dtype=np.float32) for batch_idx in xrange(self.batch_size): if (length_idx < (decoder_size - 1)): target = decoder_inputs[batch_idx][(length_idx + 1)] if ((length_idx == (decoder_size - 1)) or (target == PAD_ID)): batch_weight[batch_idx] = 0.0 batch_weights.append(batch_weight) return (batch_encoder_inputs, batch_decoder_inputs, batch_weights)
'Initializes the vocabulary.'
def __init__(self, vocab, unk_id):
self._vocab = vocab self._unk_id = unk_id
'Returns the integer id of a word string.'
def word_to_id(self, word):
if (word in self._vocab): return self._vocab[word] else: return self._unk_id
'Returns the integer word id of a word string.'
def word_to_id(self, word):
if (word in self.vocab): return self.vocab[word] else: return self.unk_id
'Returns the word string of an integer word id.'
def id_to_word(self, word_id):
if (word_id >= len(self.reverse_vocab)): return self.reverse_vocab[self.unk_id] else: return self.reverse_vocab[word_id]
'Loads a key in PKCS#1 DER or PEM format. :param keyfile: contents of a DER- or PEM-encoded file that contains the public key. :param format: the format of the file to load; \'PEM\' or \'DER\' :return: a PublicKey object'
@classmethod def load_pkcs1(cls, keyfile, format='PEM'):
methods = {'PEM': cls._load_pkcs1_pem, 'DER': cls._load_pkcs1_der} method = cls._assert_format_exists(format, methods) return method(keyfile)
'Checks whether the given file format exists in \'methods\'.'
@staticmethod def _assert_format_exists(file_format, methods):
try: return methods[file_format] except KeyError: formats = ', '.join(sorted(methods.keys())) raise ValueError(('Unsupported format: %r, try one of %s' % (file_format, formats)))
'Saves the public key in PKCS#1 DER or PEM format. :param format: the format to save; \'PEM\' or \'DER\' :returns: the DER- or PEM-encoded public key.'
def save_pkcs1(self, format='PEM'):
methods = {'PEM': self._save_pkcs1_pem, 'DER': self._save_pkcs1_der} method = self._assert_format_exists(format, methods) return method()
'Performs blinding on the message using random number \'r\'. :param message: the message, as integer, to blind. :type message: int :param r: the random number to blind with. :type r: int :return: the blinded message. :rtype: int The blinding is such that message = unblind(decrypt(blind(encrypt(message))). See https://en.wikipedia.org/wiki/Blinding_%28cryptography%29'
def blind(self, message, r):
return ((message * pow(r, self.e, self.n)) % self.n)
'Performs blinding on the message using random number \'r\'. :param blinded: the blinded message, as integer, to unblind. :param r: the random number to unblind with. :return: the original message. The blinding is such that message = unblind(decrypt(blind(encrypt(message))). See https://en.wikipedia.org/wiki/Blinding_%28cryptography%29'
def unblind(self, blinded, r):
return ((rsa.common.inverse(r, self.n) * blinded) % self.n)
'Returns the key as tuple for pickling.'
def __getstate__(self):
return (self.n, self.e)
'Sets the key from tuple.'
def __setstate__(self, state):
(self.n, self.e) = state
'Loads a key in PKCS#1 DER format. :param keyfile: contents of a DER-encoded file that contains the public key. :return: a PublicKey object First let\'s construct a DER encoded key: >>> import base64 >>> b64der = \'MAwCBQCNGmYtAgMBAAE=\' >>> der = base64.standard_b64decode(b64der) This loads the file: >>> PublicKey._load_pkcs1_der(der) PublicKey(2367317549, 65537)'
@classmethod def _load_pkcs1_der(cls, keyfile):
from pyasn1.codec.der import decoder from rsa.asn1 import AsnPubKey (priv, _) = decoder.decode(keyfile, asn1Spec=AsnPubKey()) return cls(n=int(priv['modulus']), e=int(priv['publicExponent']))
'Saves the public key in PKCS#1 DER format. @returns: the DER-encoded public key.'
def _save_pkcs1_der(self):
from pyasn1.codec.der import encoder from rsa.asn1 import AsnPubKey asn_key = AsnPubKey() asn_key.setComponentByName('modulus', self.n) asn_key.setComponentByName('publicExponent', self.e) return encoder.encode(asn_key)
'Loads a PKCS#1 PEM-encoded public key file. The contents of the file before the "-----BEGIN RSA PUBLIC KEY-----" and after the "-----END RSA PUBLIC KEY-----" lines is ignored. :param keyfile: contents of a PEM-encoded file that contains the public key. :return: a PublicKey object'
@classmethod def _load_pkcs1_pem(cls, keyfile):
der = rsa.pem.load_pem(keyfile, 'RSA PUBLIC KEY') return cls._load_pkcs1_der(der)
'Saves a PKCS#1 PEM-encoded public key file. :return: contents of a PEM-encoded file that contains the public key.'
def _save_pkcs1_pem(self):
der = self._save_pkcs1_der() return rsa.pem.save_pem(der, 'RSA PUBLIC KEY')
'Loads a PKCS#1.5 PEM-encoded public key file from OpenSSL. These files can be recognised in that they start with BEGIN PUBLIC KEY rather than BEGIN RSA PUBLIC KEY. The contents of the file before the "-----BEGIN PUBLIC KEY-----" and after the "-----END PUBLIC KEY-----" lines is ignored. :param keyfile: contents of a PEM-encoded file that contains the public key, from OpenSSL. :return: a PublicKey object'
@classmethod def load_pkcs1_openssl_pem(cls, keyfile):
der = rsa.pem.load_pem(keyfile, 'PUBLIC KEY') return cls.load_pkcs1_openssl_der(der)
'Loads a PKCS#1 DER-encoded public key file from OpenSSL. :param keyfile: contents of a DER-encoded file that contains the public key, from OpenSSL. :return: a PublicKey object'
@classmethod def load_pkcs1_openssl_der(cls, keyfile):
from rsa.asn1 import OpenSSLPubKey from pyasn1.codec.der import decoder from pyasn1.type import univ (keyinfo, _) = decoder.decode(keyfile, asn1Spec=OpenSSLPubKey()) if (keyinfo['header']['oid'] != univ.ObjectIdentifier('1.2.840.113549.1.1.1')): raise TypeError('This is not a DER-encoded OpenSSL-compatible public key') return cls._load_pkcs1_der(keyinfo['key'][1:])
'Returns the key as tuple for pickling.'
def __getstate__(self):
return (self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef)
'Sets the key from tuple.'
def __setstate__(self, state):
(self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef) = state
'Decrypts the message using blinding to prevent side-channel attacks. :param encrypted: the encrypted message :type encrypted: int :returns: the decrypted message :rtype: int'
def blinded_decrypt(self, encrypted):
blind_r = rsa.randnum.randint((self.n - 1)) blinded = self.blind(encrypted, blind_r) decrypted = rsa.core.decrypt_int(blinded, self.d, self.n) return self.unblind(decrypted, blind_r)
'Encrypts the message using blinding to prevent side-channel attacks. :param message: the message to encrypt :type message: int :returns: the encrypted message :rtype: int'
def blinded_encrypt(self, message):
blind_r = rsa.randnum.randint((self.n - 1)) blinded = self.blind(message, blind_r) encrypted = rsa.core.encrypt_int(blinded, self.d, self.n) return self.unblind(encrypted, blind_r)
'Loads a key in PKCS#1 DER format. :param keyfile: contents of a DER-encoded file that contains the private key. :return: a PrivateKey object First let\'s construct a DER encoded key: >>> import base64 >>> b64der = \'MC4CAQACBQDeKYlRAgMBAAECBQDHn4npAgMA/icCAwDfxwIDANcXAgInbwIDAMZt\' >>> der = base64.standard_b64decode(b64der) This loads the file: >>> PrivateKey._load_pkcs1_der(der) PrivateKey(3727264081, 65537, 3349121513, 65063, 57287)'
@classmethod def _load_pkcs1_der(cls, keyfile):
from pyasn1.codec.der import decoder (priv, _) = decoder.decode(keyfile) if (priv[0] != 0): raise ValueError(('Unable to read this file, version %s != 0' % priv[0])) as_ints = tuple((int(x) for x in priv[1:9])) return cls(*as_ints)
'Saves the private key in PKCS#1 DER format. @returns: the DER-encoded private key.'
def _save_pkcs1_der(self):
from pyasn1.type import univ, namedtype from pyasn1.codec.der import encoder class AsnPrivKey(univ.Sequence, ): componentType = namedtype.NamedTypes(namedtype.NamedType('version', univ.Integer()), namedtype.NamedType('modulus', univ.Integer()), namedtype.NamedType('publicExponent', univ.Integer()), namedtype.NamedType('privateExponent', univ.Integer()), namedtype.NamedType('prime1', univ.Integer()), namedtype.NamedType('prime2', univ.Integer()), namedtype.NamedType('exponent1', univ.Integer()), namedtype.NamedType('exponent2', univ.Integer()), namedtype.NamedType('coefficient', univ.Integer())) asn_key = AsnPrivKey() asn_key.setComponentByName('version', 0) asn_key.setComponentByName('modulus', self.n) asn_key.setComponentByName('publicExponent', self.e) asn_key.setComponentByName('privateExponent', self.d) asn_key.setComponentByName('prime1', self.p) asn_key.setComponentByName('prime2', self.q) asn_key.setComponentByName('exponent1', self.exp1) asn_key.setComponentByName('exponent2', self.exp2) asn_key.setComponentByName('coefficient', self.coef) return encoder.encode(asn_key)
'Loads a PKCS#1 PEM-encoded private key file. The contents of the file before the "-----BEGIN RSA PRIVATE KEY-----" and after the "-----END RSA PRIVATE KEY-----" lines is ignored. :param keyfile: contents of a PEM-encoded file that contains the private key. :return: a PrivateKey object'
@classmethod def _load_pkcs1_pem(cls, keyfile):
der = rsa.pem.load_pem(keyfile, b('RSA PRIVATE KEY')) return cls._load_pkcs1_der(der)
'Saves a PKCS#1 PEM-encoded private key file. :return: contents of a PEM-encoded file that contains the private key.'
def _save_pkcs1_pem(self):
der = self._save_pkcs1_der() return rsa.pem.save_pem(der, b('RSA PRIVATE KEY'))
'Runs the program.'
def __call__(self):
(cli, cli_args) = self.parse_cli() key = self.read_key(cli_args[0], cli.keyform) indata = self.read_infile(cli.input) print(self.operation_progressive.title(), file=sys.stderr) outdata = self.perform_operation(indata, key, cli_args) if self.has_output: self.write_outfile(outdata, cli.output)
'Parse the CLI options :returns: (cli_opts, cli_args)'
def parse_cli(self):
parser = OptionParser(usage=self.usage, description=self.description) parser.add_option('-i', '--input', type='string', help=self.input_help) if self.has_output: parser.add_option('-o', '--output', type='string', help=self.output_help) parser.add_option('--keyform', help=('Key format of the %s key - default PEM' % self.keyname), choices=('PEM', 'DER'), default='PEM') (cli, cli_args) = parser.parse_args(sys.argv[1:]) if (len(cli_args) != self.expected_cli_args): parser.print_help() raise SystemExit(1) return (cli, cli_args)
'Reads a public or private key.'
def read_key(self, filename, keyform):
print(('Reading %s key from %s' % (self.keyname, filename)), file=sys.stderr) with open(filename, 'rb') as keyfile: keydata = keyfile.read() return self.key_class.load_pkcs1(keydata, keyform)
'Read the input file'
def read_infile(self, inname):
if inname: print(('Reading input from %s' % inname), file=sys.stderr) with open(inname, 'rb') as infile: return infile.read() print('Reading input from stdin', file=sys.stderr) return sys.stdin.read()
'Write the output file'
def write_outfile(self, outdata, outname):
if outname: print(('Writing output to %s' % outname), file=sys.stderr) with open(outname, 'wb') as outfile: outfile.write(outdata) else: print('Writing output to stdout', file=sys.stderr) sys.stdout.write(outdata)
'Encrypts files.'
def perform_operation(self, indata, pub_key, cli_args=None):
return rsa.encrypt(indata, pub_key)
'Decrypts files.'
def perform_operation(self, indata, priv_key, cli_args=None):
return rsa.decrypt(indata, priv_key)
'Signs files.'
def perform_operation(self, indata, priv_key, cli_args):
hash_method = cli_args[1] if (hash_method not in HASH_METHODS): raise SystemExit(('Invalid hash method, choose one of %s' % ', '.join(HASH_METHODS))) return rsa.sign(indata, priv_key, hash_method)
'Verifies files.'
def perform_operation(self, indata, pub_key, cli_args):
signature_file = cli_args[1] with open(signature_file, 'rb') as sigfile: signature = sigfile.read() try: rsa.verify(indata, signature, pub_key) except rsa.VerificationError: raise SystemExit('Verification failed.') print('Verification OK', file=sys.stderr)
'Closes any open file handles.'
def __del__(self):
for fobj in self.file_objects: fobj.close()
'Runs the program.'
def __call__(self):
(cli, cli_args) = self.parse_cli() key = self.read_key(cli_args[0], cli.keyform) infile = self.get_infile(cli.input) outfile = self.get_outfile(cli.output) print(self.operation_progressive.title(), file=sys.stderr) self.perform_operation(infile, outfile, key, cli_args)
'Returns the input file object'
def get_infile(self, inname):
if inname: print(('Reading input from %s' % inname), file=sys.stderr) fobj = open(inname, 'rb') self.file_objects.append(fobj) else: print('Reading input from stdin', file=sys.stderr) fobj = sys.stdin return fobj
'Returns the output file object'
def get_outfile(self, outname):
if outname: print(('Will write output to %s' % outname), file=sys.stderr) fobj = open(outname, 'wb') self.file_objects.append(fobj) else: print('Will write output to stdout', file=sys.stderr) fobj = sys.stdout return fobj
'Encrypts files to VARBLOCK.'
def perform_operation(self, infile, outfile, pub_key, cli_args=None):
return rsa.bigfile.encrypt_bigfile(infile, outfile, pub_key)
'Decrypts a VARBLOCK file.'
def perform_operation(self, infile, outfile, priv_key, cli_args=None):
return rsa.bigfile.decrypt_bigfile(infile, outfile, priv_key)
'Receive EXACTLY the number of bytes requested from the file object. Blocks until the required number of bytes have been received.'
def _readall(self, file, count):
data = '' while (len(data) < count): d = file.read((count - len(data))) if (not d): raise GeneralProxyError('Connection closed unexpectedly') data += d return data
'set_proxy(proxy_type, addr[, port[, rdns[, username[, password]]]]) Sets the proxy to be used. proxy_type - The type of the proxy to be used. Three types are supported: PROXY_TYPE_SOCKS4 (including socks4a), PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP addr - The address of the server (IP or DNS). port - The port of the server. Defaults to 1080 for SOCKS servers and 8080 for HTTP proxy servers. rdns - Should DNS queries be performed on the remote side (rather than the local side). The default is True. Note: This has no effect with SOCKS4 servers. username - Username to authenticate with to the server. The default is no authentication. password - Password to authenticate with to the server. Only relevant when username is also provided.'
def set_proxy(self, proxy_type=None, addr=None, port=None, rdns=True, username=None, password=None):
self.proxy = (proxy_type, addr, port, rdns, (username.encode() if username else None), (password.encode() if password else None))
'Implements proxy connection for UDP sockets, which happens during the bind() phase.'
def bind(self, *pos, **kw):
(proxy_type, proxy_addr, proxy_port, rdns, username, password) = self.proxy if ((not proxy_type) or (self.type != socket.SOCK_DGRAM)): return _orig_socket.bind(self, *pos, **kw) if self._proxyconn: raise socket.error(EINVAL, 'Socket already bound to an address') if (proxy_type != SOCKS5): msg = 'UDP only supported by SOCKS5 proxy type' raise socket.error(EOPNOTSUPP, msg) _BaseSocket.bind(self, *pos, **kw) (_, port) = self.getsockname() dst = ('0', port) self._proxyconn = _orig_socket() proxy = self._proxy_addr() self._proxyconn.connect(proxy) UDP_ASSOCIATE = '\x03' (_, relay) = self._SOCKS5_request(self._proxyconn, UDP_ASSOCIATE, dst) (host, _) = proxy (_, port) = relay _BaseSocket.connect(self, (host, port)) self.proxy_sockname = ('0.0.0.0', 0)
'Returns the bound IP address and port number at the proxy.'
def get_proxy_sockname(self):
return self.proxy_sockname
'Returns the IP and port number of the proxy.'
def get_proxy_peername(self):
return _BaseSocket.getpeername(self)
'Returns the IP address and port number of the destination machine (note: get_proxy_peername returns the proxy)'
def get_peername(self):
return self.proxy_peername
'Negotiates a stream connection through a SOCKS5 server.'
def _negotiate_SOCKS5(self, *dest_addr):
CONNECT = '\x01' (self.proxy_peername, self.proxy_sockname) = self._SOCKS5_request(self, CONNECT, dest_addr)
'Send SOCKS5 request with given command (CMD field) and address (DST field). Returns resolved DST address that was used.'
def _SOCKS5_request(self, conn, cmd, dst):
(proxy_type, addr, port, rdns, username, password) = self.proxy writer = conn.makefile('wb') reader = conn.makefile('rb', 0) try: if (username and password): writer.write('\x05\x02\x00\x02') else: writer.write('\x05\x01\x00') writer.flush() chosen_auth = self._readall(reader, 2) if (chosen_auth[0:1] != '\x05'): raise GeneralProxyError('SOCKS5 proxy server sent invalid data') if (chosen_auth[1:2] == '\x02'): writer.write((((('\x01' + chr(len(username)).encode()) + username) + chr(len(password)).encode()) + password)) writer.flush() auth_status = self._readall(reader, 2) if (auth_status[0:1] != '\x01'): raise GeneralProxyError('SOCKS5 proxy server sent invalid data') if (auth_status[1:2] != '\x00'): raise SOCKS5AuthError('SOCKS5 authentication failed') elif (chosen_auth[1:2] != '\x00'): if (chosen_auth[1:2] == '\xff'): raise SOCKS5AuthError('All offered SOCKS5 authentication methods were rejected') else: raise GeneralProxyError('SOCKS5 proxy server sent invalid data') writer.write((('\x05' + cmd) + '\x00')) resolved = self._write_SOCKS5_address(dst, writer) writer.flush() resp = self._readall(reader, 3) if (resp[0:1] != '\x05'): raise GeneralProxyError('SOCKS5 proxy server sent invalid data') status = ord(resp[1:2]) if (status != 0): error = SOCKS5_ERRORS.get(status, 'Unknown error') raise SOCKS5Error('{0:#04x}: {1}'.format(status, error)) bnd = self._read_SOCKS5_address(reader) return (resolved, bnd) finally: reader.close() writer.close()
'Return the host and port packed for the SOCKS5 protocol, and the resolved address as a tuple object.'
def _write_SOCKS5_address(self, addr, file):
(host, port) = addr (proxy_type, _, _, rdns, username, password) = self.proxy try: addr_bytes = socket.inet_aton(host) file.write(('\x01' + addr_bytes)) host = socket.inet_ntoa(addr_bytes) except socket.error: if rdns: host_bytes = host.encode('idna') file.write((('\x03' + chr(len(host_bytes)).encode()) + host_bytes)) else: addr_bytes = socket.inet_aton(socket.gethostbyname(host)) file.write(('\x01' + addr_bytes)) host = socket.inet_ntoa(addr_bytes) file.write(struct.pack('>H', port)) return (host, port)
'Negotiates a connection through a SOCKS4 server.'
def _negotiate_SOCKS4(self, dest_addr, dest_port):
(proxy_type, addr, port, rdns, username, password) = self.proxy writer = self.makefile('wb') reader = self.makefile('rb', 0) try: remote_resolve = False try: addr_bytes = socket.inet_aton(dest_addr) except socket.error: if rdns: addr_bytes = '\x00\x00\x00\x01' remote_resolve = True else: addr_bytes = socket.inet_aton(socket.gethostbyname(dest_addr)) writer.write(struct.pack('>BBH', 4, 1, dest_port)) writer.write(addr_bytes) if username: writer.write(username) writer.write('\x00') if remote_resolve: writer.write((dest_addr.encode('idna') + '\x00')) writer.flush() resp = self._readall(reader, 8) if (resp[0:1] != '\x00'): raise GeneralProxyError('SOCKS4 proxy server sent invalid data') status = ord(resp[1:2]) if (status != 90): error = SOCKS4_ERRORS.get(status, 'Unknown error') raise SOCKS4Error('{0:#04x}: {1}'.format(status, error)) self.proxy_sockname = (socket.inet_ntoa(resp[4:]), struct.unpack('>H', resp[2:4])[0]) if remote_resolve: self.proxy_peername = (socket.inet_ntoa(addr_bytes), dest_port) else: self.proxy_peername = (dest_addr, dest_port) finally: reader.close() writer.close()
'Negotiates a connection through an HTTP server. NOTE: This currently only supports HTTP CONNECT-style proxies.'
def _negotiate_HTTP(self, dest_addr, dest_port):
(proxy_type, addr, port, rdns, username, password) = self.proxy addr = (dest_addr if rdns else socket.gethostbyname(dest_addr)) self.sendall(((((((('CONNECT ' + addr.encode('idna')) + ':') + str(dest_port).encode()) + ' HTTP/1.1\r\n') + 'Host: ') + dest_addr.encode('idna')) + '\r\n\r\n')) fobj = self.makefile() status_line = fobj.readline() fobj.close() if (not status_line): raise GeneralProxyError('Connection closed unexpectedly') try: (proto, status_code, status_msg) = status_line.split(' ', 2) except ValueError: raise GeneralProxyError('HTTP proxy server sent invalid response') if (not proto.startswith('HTTP/')): raise GeneralProxyError('Proxy server does not appear to be an HTTP proxy') try: status_code = int(status_code) except ValueError: raise HTTPError('HTTP proxy server did not return a valid HTTP status') if (status_code != 200): error = '{0}: {1}'.format(status_code, status_msg) if (status_code in (400, 403, 405)): error += '\n[*] Note: The HTTP proxy server may not be supported by PySocks (must be a CONNECT tunnel proxy)' raise HTTPError(error) self.proxy_sockname = ('0.0.0.0', 0) self.proxy_peername = (addr, dest_port)
'Connects to the specified destination through a proxy. Uses the same API as socket\'s connect(). To select the proxy server, use set_proxy(). dest_pair - 2-tuple of (IP/hostname, port).'
def connect(self, dest_pair):
(dest_addr, dest_port) = dest_pair if (self.type == socket.SOCK_DGRAM): if (not self._proxyconn): self.bind(('', 0)) dest_addr = socket.gethostbyname(dest_addr) if ((dest_addr == '0.0.0.0') and (not dest_port)): self.proxy_peername = None else: self.proxy_peername = (dest_addr, dest_port) return (proxy_type, proxy_addr, proxy_port, rdns, username, password) = self.proxy if ((not isinstance(dest_pair, (list, tuple))) or (len(dest_pair) != 2) or (not dest_addr) or (not isinstance(dest_port, int))): raise GeneralProxyError('Invalid destination-connection (host, port) pair') if (proxy_type is None): self.proxy_peername = dest_pair _BaseSocket.connect(self, (dest_addr, dest_port)) return proxy_addr = self._proxy_addr() try: _BaseSocket.connect(self, proxy_addr) except socket.error as error: self.close() (proxy_addr, proxy_port) = proxy_addr proxy_server = '{0}:{1}'.format(proxy_addr, proxy_port) printable_type = PRINTABLE_PROXY_TYPES[proxy_type] msg = 'Error connecting to {0} proxy {1}'.format(printable_type, proxy_server) raise ProxyConnectionError(msg, error) else: try: negotiate = self._proxy_negotiators[proxy_type] negotiate(self, dest_addr, dest_port) except socket.error as error: self.close() raise GeneralProxyError('Socket error', error) except ProxyError: self.close() raise
'Return proxy address to connect to as tuple object'
def _proxy_addr(self):
(proxy_type, proxy_addr, proxy_port, rdns, username, password) = self.proxy proxy_port = (proxy_port or DEFAULT_PORTS.get(proxy_type)) if (not proxy_port): raise GeneralProxyError('Invalid proxy type') return (proxy_addr, proxy_port)
'ASN.1 tag class Returns : :py:class:`int` Tag class'
@property def tagClass(self):
return self.__tagClass
'ASN.1 tag format Returns : :py:class:`int` Tag format'
@property def tagFormat(self):
return self.__tagFormat
'ASN.1 tag ID Returns : :py:class:`int` Tag ID'
@property def tagId(self):
return self.__tagId
'Return base ASN.1 tag Returns : :class:`~pyasn1.type.tag.Tag` Base tag of this *TagSet*'
@property def baseTag(self):
return self.__baseTag
'Return ASN.1 tags Returns : :py:class:`tuple` Tuple of :class:`~pyasn1.type.tag.Tag` objects that this *TagSet* contains'
@property def superTags(self):
return self.__superTags
'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'
def tagExplicitly(self, superTag):
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)
'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'
def tagImplicitly(self, superTag):
if self.__superTags: superTag = Tag(superTag.tagClass, self.__superTags[(-1)].tagFormat, superTag.tagId) return (self[:(-1)] + superTag)
'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` `True` if callee is a supertype of *tagSet*'
def isSuperTagSetOf(self, tagSet):
if (len(tagSet) < self.__lenOfSuperTags): return False return (self.__superTags == tagSet[:self.__lenOfSuperTags])
'For |ASN.1| type is equivalent to *tagSet*'
@property def effectiveTagSet(self):
return self._tagSet
'Return a :class:`~pyasn1.type.tagmap.TagMap` object mapping ASN.1 tags to ASN.1 objects within callee object.'
@property def tagMap(self):
try: return self._tagMap except AttributeError: self._tagMap = tagmap.TagMap({self._tagSet: self}) return self._tagMap
'Examine |ASN.1| type for equality with other ASN.1 type. ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints (:py:mod:`~pyasn1.type.constraint`) are examined when carrying out ASN.1 types comparison. No Python inheritance relationship between PyASN1 objects is considered. Parameters other: a pyasn1 type object Class instance representing ASN.1 type. Returns : :class:`bool` :class:`True` if *other* is |ASN.1| type, :class:`False` otherwise.'
def isSameTypeWith(self, other, matchTags=True, matchConstraints=True):
return ((self is other) or (((not matchTags) or (self._tagSet == other.tagSet)) and ((not matchConstraints) or (self._subtypeSpec == other.subtypeSpec))))
'Examine |ASN.1| type for subtype relationship with other ASN.1 type. ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints (:py:mod:`~pyasn1.type.constraint`) are examined when carrying out ASN.1 types comparison. No Python inheritance relationship between PyASN1 objects is considered. Parameters other: a pyasn1 type object Class instance representing ASN.1 type. Returns : :class:`bool` :class:`True` if *other* is a subtype of |ASN.1| type, :class:`False` otherwise.'
def isSuperTypeOf(self, other, matchTags=True, matchConstraints=True):
return (((not matchTags) or self._tagSet.isSuperTagSetOf(other.tagSet)) and ((not matchConstraints) or self._subtypeSpec.isSuperTypeOf(other.subtypeSpec)))
'Indicate if |ASN.1| object 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. Returns : :class:`bool` :class:`True` if object represents ASN.1 value and type, :class:`False` if object represents just ASN.1 type.'
@property def isValue(self):
return (self._value is not noValue)
'Create 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:`tuple`, :class:`str` or |ASN.1| object Initialization value to pass to new ASN.1 object instead of inheriting one from the caller. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing ASN.1 tag(s) to use in new object instead of inheriting from the caller subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing ASN.1 subtype constraint(s) to use in new object instead of inheriting from the caller Returns new instance of |ASN.1| type/value'
def clone(self, value=noValue, tagSet=None, subtypeSpec=None):
isModified = False if ((value is None) or (value is noValue)): value = self._value else: isModified = True if ((tagSet is None) or (tagSet is noValue)): tagSet = self._tagSet else: isModified = True if ((subtypeSpec is None) or (subtypeSpec is noValue)): subtypeSpec = self._subtypeSpec else: isModified = True if isModified: return self.__class__(value, tagSet, subtypeSpec) else: return self
'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:`str` or |ASN.1| object Initialization value to pass to new ASN.1 object instead of inheriting one from the caller. implicitTag: :py:class:`~pyasn1.type.tag.Tag` Implicitly apply given ASN.1 tag object to caller\'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 caller\'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 caller, then use the result as new object\'s ASN.1 constraints. Returns new instance of |ASN.1| type/value'
def subtype(self, value=noValue, implicitTag=None, explicitTag=None, subtypeSpec=None):
isModified = False if ((value is None) or (value is noValue)): value = self._value else: isModified = True if ((implicitTag is not None) and (implicitTag is not noValue)): tagSet = self._tagSet.tagImplicitly(implicitTag) isModified = True elif ((explicitTag is not None) and (explicitTag is not noValue)): tagSet = self._tagSet.tagExplicitly(explicitTag) isModified = True else: tagSet = self._tagSet if ((subtypeSpec is None) or (subtypeSpec is noValue)): subtypeSpec = self._subtypeSpec else: subtypeSpec = (self._subtypeSpec + subtypeSpec) isModified = True if isModified: return self.__class__(value, tagSet, subtypeSpec) else: return self
'Provide human-friendly printable object representation. Returns : :class:`str` human-friendly type and/or value representation.'
def prettyPrint(self, scope=0):
if self.isValue: return self.prettyOut(self._value) else: return '<no value>'
'Create 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 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) sizeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 size constraint(s) Returns new instance of |ASN.1| type/value'
def clone(self, tagSet=None, subtypeSpec=None, sizeSpec=None, cloneValueFlag=None):
if (tagSet is None): tagSet = self._tagSet if (subtypeSpec is None): subtypeSpec = self._subtypeSpec if (sizeSpec is None): sizeSpec = self._sizeSpec clone = self.__class__(self._componentType, tagSet, subtypeSpec, sizeSpec) if cloneValueFlag: self._cloneComponentValues(clone, cloneValueFlag) return clone
'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 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) sizeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 size constraint(s) Returns new instance of |ASN.1| type/value'
def subtype(self, implicitTag=None, explicitTag=None, subtypeSpec=None, sizeSpec=None, cloneValueFlag=None):
if ((implicitTag is not None) and (implicitTag is not noValue)): tagSet = self._tagSet.tagImplicitly(implicitTag) elif ((explicitTag is not None) and (explicitTag is not noValue)): tagSet = self._tagSet.tagExplicitly(explicitTag) else: tagSet = self._tagSet if ((subtypeSpec is None) or (subtypeSpec is noValue)): subtypeSpec = self._subtypeSpec else: subtypeSpec = (self._subtypeSpec + subtypeSpec) if ((sizeSpec is None) or (sizeSpec is noValue)): sizeSpec = self._sizeSpec else: sizeSpec += self._sizeSpec clone = self.__class__(self._componentType, tagSet, subtypeSpec, sizeSpec) if cloneValueFlag: self._cloneComponentValues(clone, cloneValueFlag) return clone
'Return *TagSet* to ASN.1 type map present in callee *TagMap*'
@property def presentTypes(self):
return self.__presentTypes
'Return *TagSet* collection unconditionally absent in callee *TagMap*'
@property def skipTypes(self):
return self.__skipTypes
'Return default ASN.1 type being returned for any missing *TagSet*'
@property def defaultType(self):
return self.__defaultType
'Create 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:`int`, :class:`str` or |ASN.1| object Initialization value to pass to new ASN.1 object instead of inheriting one from the caller. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing ASN.1 tag(s) to use in new object instead of inheriting from the caller subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing ASN.1 subtype constraint(s) to use in new object instead of inheriting from the caller namedValues: :py:class:`~pyasn1.type.namedval.NamedValues` Object representing symbolic aliases for numbers to use instead of inheriting from caller Returns new instance of |ASN.1| type/value'
def clone(self, value=noValue, tagSet=None, subtypeSpec=None, namedValues=None):
isModified = False if ((value is None) or (value is noValue)): value = self._value else: isModified = True if ((tagSet is None) or (tagSet is noValue)): tagSet = self._tagSet else: isModified = True if ((subtypeSpec is None) or (subtypeSpec is noValue)): subtypeSpec = self._subtypeSpec else: isModified = True if ((namedValues is None) or (namedValues is noValue)): namedValues = self.__namedValues else: isModified = True if isModified: return self.__class__(value, tagSet, subtypeSpec, namedValues) else: return self
'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:`int`, :class:`str` or |ASN.1| object Initialization value to pass to new ASN.1 object instead of inheriting one from the caller. implicitTag: :py:class:`~pyasn1.type.tag.Tag` Implicitly apply given ASN.1 tag object to caller\'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 caller\'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 caller, then use the result as new object\'s ASN.1 constraints. namedValues: :py:class:`~pyasn1.type.namedval.NamedValues` Add given object representing symbolic aliases for numbers to one of the caller, then use the result as new object\'s named numbers. Returns new instance of |ASN.1| type/value'
def subtype(self, value=noValue, implicitTag=None, explicitTag=None, subtypeSpec=None, namedValues=None):
isModified = False if ((value is None) or (value is noValue)): value = self._value else: isModified = True if ((implicitTag is not None) and (implicitTag is not noValue)): tagSet = self._tagSet.tagImplicitly(implicitTag) isModified = True elif ((explicitTag is not None) and (explicitTag is not noValue)): tagSet = self._tagSet.tagExplicitly(explicitTag) isModified = True else: tagSet = self._tagSet if ((subtypeSpec is None) or (subtypeSpec is noValue)): subtypeSpec = self._subtypeSpec else: subtypeSpec = (self._subtypeSpec + subtypeSpec) isModified = True if ((namedValues is None) or (namedValues is noValue)): namedValues = self.__namedValues else: namedValues = (namedValues + self.__namedValues) isModified = True if isModified: return self.__class__(value, tagSet, subtypeSpec, namedValues) else: return self
'Create 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:`int`, :class:`str` or |ASN.1| object Initialization value to pass to new ASN.1 object instead of inheriting one from the caller. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing ASN.1 tag(s) to use in new object instead of inheriting from the caller subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing ASN.1 subtype constraint(s) to use in new object instead of inheriting from the caller namedValues: :py:class:`~pyasn1.type.namedval.NamedValues` Class instance representing BitString type enumerations 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\'. Returns new instance of |ASN.1| type/value'
def clone(self, value=noValue, tagSet=None, subtypeSpec=None, namedValues=None, binValue=noValue, hexValue=noValue):
isModified = False if (((value is None) or (value is noValue)) and (binValue is noValue) and (hexValue is noValue)): value = self._value else: isModified = True if ((tagSet is None) or (tagSet is noValue)): tagSet = self._tagSet else: isModified = True if ((subtypeSpec is None) or (subtypeSpec is noValue)): subtypeSpec = self._subtypeSpec else: isModified = True if ((namedValues is None) or (namedValues is noValue)): namedValues = self.__namedValues else: isModified = True if isModified: return self.__class__(value, tagSet, subtypeSpec, namedValues, binValue, hexValue) else: return self
'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:`int`, :class:`str` or |ASN.1| object Initialization value to pass to new ASN.1 object instead of inheriting one from the caller. implicitTag: :py:class:`~pyasn1.type.tag.Tag` Implicitly apply given ASN.1 tag object to caller\'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 caller\'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 caller, then use the result as new object\'s ASN.1 constraints. namedValues: :py:class:`~pyasn1.type.namedval.NamedValues` Add given object representing symbolic aliases for numbers to one of the caller, then use the result as new object\'s named 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\'. Returns new instance of |ASN.1| type/value'
def subtype(self, value=noValue, implicitTag=None, explicitTag=None, subtypeSpec=None, namedValues=None, binValue=noValue, hexValue=noValue):
isModified = False if (((value is None) or (value is noValue)) and (binValue is noValue) and (hexValue is noValue)): value = self._value else: isModified = True if ((implicitTag is not None) and (implicitTag is not noValue)): tagSet = self._tagSet.tagImplicitly(implicitTag) isModified = True elif ((explicitTag is not None) and (explicitTag is not noValue)): tagSet = self._tagSet.tagExplicitly(explicitTag) isModified = True else: tagSet = self._tagSet if ((subtypeSpec is None) or (subtypeSpec is noValue)): subtypeSpec = self._subtypeSpec else: subtypeSpec = (self._subtypeSpec + subtypeSpec) isModified = True if ((namedValues is None) or (namedValues is noValue)): namedValues = self.__namedValues else: namedValues = (namedValues + self.__namedValues) isModified = True if isModified: return self.__class__(value, tagSet, subtypeSpec, namedValues, binValue, hexValue) else: return 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.'
def asNumbers(self):
return tuple(octets.octs2ints(self.asOctets()))
'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.'
def asOctets(self):
return integer.to_bytes(self._value, length=len(self))
'Get |ASN.1| value as a single integer value.'
def asInteger(self):
return self._value
'Get |ASN.1| value as a text string of bits.'
def asBinary(self):
binString = binary.bin(self._value)[2:] return (('0' * (len(self._value) - len(binString))) + binString)
'Create 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:`str`, :class:`bytes` or |ASN.1| object Initialization value to pass to new ASN.1 object instead of inheriting one from the caller. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing ASN.1 tag(s) to use in new object instead of inheriting from the caller subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing ASN.1 subtype constraint(s) to use in new object instead of inheriting from the caller encoding: :py:class:`str` Unicode codec ID to encode/decode :class:`unicode` (Python 2) or :class:`str` (Python 3) the payload when |ASN.1| object is used in string context. binValue: :py:class:`str` Binary string initializer. Example: \'10110011\'. hexValue: :py:class:`str` Hexadecimal string initializer. Example: \'DEADBEEF\'. Returns new instance of |ASN.1| type/value'
def clone(self, value=noValue, tagSet=None, subtypeSpec=None, encoding=None, binValue=noValue, hexValue=noValue):
isModified = False if (((value is None) or (value is noValue)) and (binValue is noValue) and (hexValue is noValue)): value = self._value else: isModified = True if ((tagSet is None) or (tagSet is noValue)): tagSet = self._tagSet else: isModified = True if ((subtypeSpec is None) or (subtypeSpec is noValue)): subtypeSpec = self._subtypeSpec else: isModified = True if ((encoding is None) or (encoding is noValue)): encoding = self._encoding else: isModified = True if isModified: return self.__class__(value, tagSet, subtypeSpec, encoding, binValue, hexValue) else: return self
'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:`str`, :class:`bytes` or |ASN.1| object Initialization value to pass to new ASN.1 object instead of inheriting one from the caller. implicitTag: :py:class:`~pyasn1.type.tag.Tag` Implicitly apply given ASN.1 tag object to |ASN.1| object tag set :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 |ASN.1| object tag set :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 caller, then use the result as new object\'s ASN.1 constraints. encoding: :py:class:`str` Unicode codec ID to encode/decode :class:`unicode` (Python 2) or :class:`str` (Python 3) the payload when *OctetString* object is used in string context. binValue: :py:class:`str` Binary string initializer. Example: \'10110011\'. hexValue: :py:class:`str` Hexadecimal string initializer. Example: \'DEADBEEF\'. Returns new instance of |ASN.1| type/value'
def subtype(self, value=noValue, implicitTag=None, explicitTag=None, subtypeSpec=None, encoding=None, binValue=noValue, hexValue=noValue):
isModified = False if (((value is None) or (value is noValue)) and (binValue is noValue) and (hexValue is noValue)): value = self._value else: isModified = True if ((implicitTag is not None) and (implicitTag is not noValue)): tagSet = self._tagSet.tagImplicitly(implicitTag) isModified = True elif ((explicitTag is not None) and (explicitTag is not noValue)): tagSet = self._tagSet.tagExplicitly(explicitTag) isModified = True else: tagSet = self._tagSet if ((subtypeSpec is None) or (subtypeSpec is noValue)): subtypeSpec = self._subtypeSpec else: subtypeSpec = (self._subtypeSpec + subtypeSpec) isModified = True if ((encoding is None) or (encoding is noValue)): encoding = self._encoding else: isModified = True if isModified: return self.__class__(value, tagSet, subtypeSpec, encoding, binValue, hexValue) else: return self
'Create 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:`str` or |ASN.1| object Initialization value to pass to new ASN.1 object instead of inheriting one from the caller. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing ASN.1 tag(s) to use in new object instead of inheriting from the caller Returns : :py:class:`~pyasn1.type.univ.Null` new instance of NULL type/value'
def clone(self, value=noValue, tagSet=None):
return OctetString.clone(self, value, tagSet)
'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:`int`, :class:`str` or |ASN.1| object Initialization value to pass to new ASN.1 object instead of inheriting one from the caller. implicitTag: :py:class:`~pyasn1.type.tag.Tag` Implicitly apply given ASN.1 tag object to caller\'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 caller\'s :py:class:`~pyasn1.type.tag.TagSet`, then use the result as new object\'s ASN.1 tag(s). Returns : :py:class:`~pyasn1.type.univ.Null` new instance of NULL type/value'
def subtype(self, value=noValue, implicitTag=None, explicitTag=None):
return OctetString.subtype(self, value, implicitTag, explicitTag)
'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` :class:`True` if this |ASN.1| object is a parent (e.g. prefix) of the other |ASN.1| object or :class:`False` otherwise.'
def isPrefixOf(self, other):
l = len(self) if (l <= len(other)): if (self._value[:l] == other[:l]): return True return False
'Create 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:`tuple`, :class:`float` or |ASN.1| object Initialization value to pass to new ASN.1 object instead of inheriting one from the caller. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing ASN.1 tag(s) to use in new object instead of inheriting from the caller subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing ASN.1 subtype constraint(s) to use in new object instead of inheriting from the caller Returns new instance of |ASN.1| type/value'
def clone(self, value=noValue, tagSet=None, subtypeSpec=None):
return base.AbstractSimpleAsn1Item.clone(self, value, tagSet, subtypeSpec)