desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'This extension defines policies in CA certificates under which
certificates may be issued. In end-entity certificates, the inclusion
of a policy indicates the issuance of the certificate follows the
policy.
:return:
None or a CertificatePolicies object'
| @property
def certificate_policies_value(self):
| if (not self._processed_extensions):
self._set_extensions()
return self._certificate_policies_value
|
'This extension allows mapping policy OIDs to other OIDs. This is used
to allow different policies to be treated as equivalent in the process
of validation.
:return:
None or a PolicyMappings object'
| @property
def policy_mappings_value(self):
| if (not self._processed_extensions):
self._set_extensions()
return self._policy_mappings_value
|
'This extension helps in identifying the public key with which to
validate the authenticity of the certificate.
:return:
None or an AuthorityKeyIdentifier object'
| @property
def authority_key_identifier_value(self):
| if (not self._processed_extensions):
self._set_extensions()
return self._authority_key_identifier_value
|
'This extension is used to control if policy mapping is allowed and
when policies are required.
:return:
None or a PolicyConstraints object'
| @property
def policy_constraints_value(self):
| if (not self._processed_extensions):
self._set_extensions()
return self._policy_constraints_value
|
'This extension is used to help locate any available delta CRLs
:return:
None or an CRLDistributionPoints object'
| @property
def freshest_crl_value(self):
| if (not self._processed_extensions):
self._set_extensions()
return self._freshest_crl_value
|
'This extension is used to prevent mapping of the any policy to
specific requirements
:return:
None or a Integer object'
| @property
def inhibit_any_policy_value(self):
| if (not self._processed_extensions):
self._set_extensions()
return self._inhibit_any_policy_value
|
'This extension is used to define additional purposes for the public key
beyond what is contained in the basic constraints.
:return:
None or an ExtKeyUsageSyntax object'
| @property
def extended_key_usage_value(self):
| if (not self._processed_extensions):
self._set_extensions()
return self._extended_key_usage_value
|
'This extension is used to locate the CA certificate used to sign this
certificate, or the OCSP responder for this certificate.
:return:
None or an AuthorityInfoAccessSyntax object'
| @property
def authority_information_access_value(self):
| if (not self._processed_extensions):
self._set_extensions()
return self._authority_information_access_value
|
'This extension is used to access information about the subject of this
certificate.
:return:
None or a SubjectInfoAccessSyntax object'
| @property
def subject_information_access_value(self):
| if (not self._processed_extensions):
self._set_extensions()
return self._subject_information_access_value
|
'This extension is used to list the TLS features a server must respond
with if a client initiates a request supporting them.
:return:
None or a Features object'
| @property
def tls_feature_value(self):
| if (not self._processed_extensions):
self._set_extensions()
return self._tls_feature_value
|
'This extension is used on certificates of OCSP responders, indicating
that revocation information for the certificate should never need to
be verified, thus preventing possible loops in path validation.
:return:
None or a Null object (if present)'
| @property
def ocsp_no_check_value(self):
| if (not self._processed_extensions):
self._set_extensions()
return self._ocsp_no_check_value
|
':return:
A byte string of the signature'
| @property
def signature(self):
| return self[u'signature_value'].native
|
':return:
A unicode string of "rsassa_pkcs1v15", "rsassa_pss", "dsa", "ecdsa"'
| @property
def signature_algo(self):
| return self[u'signature_algorithm'].signature_algo
|
':return:
A unicode string of "md2", "md5", "sha1", "sha224", "sha256",
"sha384", "sha512", "sha512_224", "sha512_256"'
| @property
def hash_algo(self):
| return self[u'signature_algorithm'].hash_algo
|
':return:
The PublicKeyInfo object for this certificate'
| @property
def public_key(self):
| return self[u'tbs_certificate'][u'subject_public_key_info']
|
':return:
The Name object for the subject of this certificate'
| @property
def subject(self):
| return self[u'tbs_certificate'][u'subject']
|
':return:
The Name object for the issuer of this certificate'
| @property
def issuer(self):
| return self[u'tbs_certificate'][u'issuer']
|
':return:
An integer of the certificate\'s serial number'
| @property
def serial_number(self):
| return self[u'tbs_certificate'][u'serial_number'].native
|
':return:
None or a byte string of the certificate\'s key identifier from the
key identifier extension'
| @property
def key_identifier(self):
| if (not self.key_identifier_value):
return None
return self.key_identifier_value.native
|
':return:
A byte string of the SHA-256 hash of the issuer concatenated with
the ascii character ":", concatenated with the serial number as
an ascii string'
| @property
def issuer_serial(self):
| if (self._issuer_serial is None):
self._issuer_serial = ((self.issuer.sha256 + ':') + str_cls(self.serial_number).encode(u'ascii'))
return self._issuer_serial
|
':return:
None or a byte string of the key_identifier from the authority key
identifier extension'
| @property
def authority_key_identifier(self):
| if (not self.authority_key_identifier_value):
return None
return self.authority_key_identifier_value[u'key_identifier'].native
|
':return:
None or a byte string of the SHA-256 hash of the isser from the
authority key identifier extension concatenated with the ascii
character ":", concatenated with the serial number from the
authority key identifier extension as an ascii string'
| @property
def authority_issuer_serial(self):
| if (self._authority_issuer_serial is False):
akiv = self.authority_key_identifier_value
if (akiv and akiv[u'authority_cert_issuer'].native):
issuer = self.authority_key_identifier_value[u'authority_cert_issuer'][0].chosen
issuer = issuer.untag()
authority_serial = self.authority_key_identifier_value[u'authority_cert_serial_number'].native
self._authority_issuer_serial = ((issuer.sha256 + ':') + str_cls(authority_serial).encode(u'ascii'))
else:
self._authority_issuer_serial = None
return self._authority_issuer_serial
|
'Returns complete CRL URLs - does not include delta CRLs
:return:
A list of zero or more DistributionPoint objects'
| @property
def crl_distribution_points(self):
| if (self._crl_distribution_points is None):
self._crl_distribution_points = self._get_http_crl_distribution_points(self.crl_distribution_points_value)
return self._crl_distribution_points
|
'Returns delta CRL URLs - does not include complete CRLs
:return:
A list of zero or more DistributionPoint objects'
| @property
def delta_crl_distribution_points(self):
| if (self._delta_crl_distribution_points is None):
self._delta_crl_distribution_points = self._get_http_crl_distribution_points(self.freshest_crl_value)
return self._delta_crl_distribution_points
|
'Fetches the DistributionPoint object for non-relative, HTTP CRLs
referenced by the certificate
:param crl_distribution_points:
A CRLDistributionPoints object to grab the DistributionPoints from
:return:
A list of zero or more DistributionPoint objects'
| def _get_http_crl_distribution_points(self, crl_distribution_points):
| output = []
if (crl_distribution_points is None):
return []
for distribution_point in crl_distribution_points:
distribution_point_name = distribution_point[u'distribution_point']
if (distribution_point_name is VOID):
continue
if (distribution_point_name.name == u'name_relative_to_crl_issuer'):
continue
for general_name in distribution_point_name.chosen:
if (general_name.name == u'uniform_resource_identifier'):
output.append(distribution_point)
return output
|
':return:
A list of zero or more unicode strings of the OCSP URLs for this
cert'
| @property
def ocsp_urls(self):
| if (not self.authority_information_access_value):
return []
output = []
for entry in self.authority_information_access_value:
if (entry[u'access_method'].native == u'ocsp'):
location = entry[u'access_location']
if (location.name != u'uniform_resource_identifier'):
continue
url = location.native
if (url.lower()[0:7] == u'http://'):
output.append(url)
return output
|
':return:
A list of unicode strings of valid domain names for the certificate.
Wildcard certificates will have a domain in the form: *.example.com'
| @property
def valid_domains(self):
| if (self._valid_domains is None):
self._valid_domains = []
if self.subject_alt_name_value:
for general_name in self.subject_alt_name_value:
if ((general_name.name == u'dns_name') and (general_name.native not in self._valid_domains)):
self._valid_domains.append(general_name.native)
else:
pattern = re.compile(u'^(\\*\\.)?(?:[a-zA-Z0-9](?:[a-zA-Z0-9\\-]*[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}$')
for rdn in self.subject.chosen:
for name_type_value in rdn:
if (name_type_value[u'type'].native == u'common_name'):
value = name_type_value[u'value'].native
if pattern.match(value):
self._valid_domains.append(value)
return self._valid_domains
|
':return:
A list of unicode strings of valid IP addresses for the certificate'
| @property
def valid_ips(self):
| if (self._valid_ips is None):
self._valid_ips = []
if self.subject_alt_name_value:
for general_name in self.subject_alt_name_value:
if (general_name.name == u'ip_address'):
self._valid_ips.append(general_name.native)
return self._valid_ips
|
':return;
A boolean - if the certificate is marked as a CA'
| @property
def ca(self):
| return (self.basic_constraints_value and self.basic_constraints_value[u'ca'].native)
|
':return;
None or an integer of the maximum path length'
| @property
def max_path_length(self):
| if (not self.ca):
return None
return self.basic_constraints_value[u'path_len_constraint'].native
|
':return:
A boolean - if the certificate is self-issued, as defined by RFC
5280'
| @property
def self_issued(self):
| if (self._self_issued is None):
self._self_issued = (self.subject == self.issuer)
return self._self_issued
|
':return:
A unicode string of "yes", "no" or "maybe". The "maybe" result will
be returned if the certificate does not contain a key identifier
extension, but is issued by the subject. In this case the
certificate signature will need to be verified using the subject
public key to determine a "yes" or "no" answer.'
| @property
def self_signed(self):
| if (self._self_signed is None):
self._self_signed = u'no'
if self.self_issued:
if self.key_identifier:
if (not self.authority_key_identifier):
self._self_signed = u'yes'
elif (self.authority_key_identifier == self.key_identifier):
self._self_signed = u'yes'
else:
self._self_signed = u'maybe'
return self._self_signed
|
':return:
The SHA-1 hash of the DER-encoded bytes of this complete certificate'
| @property
def sha1(self):
| if (self._sha1 is None):
self._sha1 = hashlib.sha1(self.dump()).digest()
return self._sha1
|
':return:
A unicode string of the SHA-1 hash, formatted using hex encoding
with a space between each pair of characters, all uppercase'
| @property
def sha1_fingerprint(self):
| return u' '.join(((u'%02X' % c) for c in bytes_to_list(self.sha1)))
|
':return:
The SHA-256 hash of the DER-encoded bytes of this complete
certificate'
| @property
def sha256(self):
| if (self._sha256 is None):
self._sha256 = hashlib.sha256(self.dump()).digest()
return self._sha256
|
'Check if a domain name or IP address is valid according to the
certificate
:param domain_ip:
A unicode string of a domain name or IP address
:return:
A boolean - if the domain or IP is valid for the certificate'
| def is_valid_domain_ip(self, domain_ip):
| if (not isinstance(domain_ip, str_cls)):
raise TypeError(unwrap(u'\n domain_ip must be a unicode string, not %s\n ', type_name(domain_ip)))
encoded_domain_ip = domain_ip.encode(u'idna').decode(u'ascii').lower()
is_ipv6 = (encoded_domain_ip.find(u':') != (-1))
is_ipv4 = ((not is_ipv6) and re.match(u'^\\d+\\.\\d+\\.\\d+\\.\\d+$', encoded_domain_ip))
is_domain = ((not is_ipv6) and (not is_ipv4))
if is_domain:
if (not self.valid_domains):
return False
domain_labels = encoded_domain_ip.split(u'.')
for valid_domain in self.valid_domains:
encoded_valid_domain = valid_domain.encode(u'idna').decode(u'ascii').lower()
valid_domain_labels = encoded_valid_domain.split(u'.')
if (len(valid_domain_labels) != len(domain_labels)):
continue
if (valid_domain_labels == domain_labels):
return True
is_wildcard = self._is_wildcard_domain(encoded_valid_domain)
if (is_wildcard and self._is_wildcard_match(domain_labels, valid_domain_labels)):
return True
return False
if (not self.valid_ips):
return False
family = (socket.AF_INET if is_ipv4 else socket.AF_INET6)
normalized_ip = inet_pton(family, encoded_domain_ip)
for valid_ip in self.valid_ips:
valid_family = (socket.AF_INET if (valid_ip.find(u'.') != (-1)) else socket.AF_INET6)
normalized_valid_ip = inet_pton(valid_family, valid_ip)
if (normalized_valid_ip == normalized_ip):
return True
return False
|
'Checks if a domain is a valid wildcard according to
https://tools.ietf.org/html/rfc6125#section-6.4.3
:param domain:
A unicode string of the domain name, where any U-labels from an IDN
have been converted to A-labels
:return:
A boolean - if the domain is a valid wildcard domain'
| def _is_wildcard_domain(self, domain):
| if (domain.count(u'*') != 1):
return False
labels = domain.lower().split(u'.')
if (not labels):
return False
if (labels[0].find(u'*') == (-1)):
return False
if (labels[0][0:4] == u'xn--'):
return False
return True
|
'Determines if the labels in a domain are a match for labels from a
wildcard valid domain name
:param domain_labels:
A list of unicode strings, with A-label form for IDNs, of the labels
in the domain name to check
:param valid_domain_labels:
A list of unicode strings, with A-label form for IDNs, of the labels
in a wildcard domain pattern
:return:
A boolean - if the domain matches the valid domain'
| def _is_wildcard_match(self, domain_labels, valid_domain_labels):
| first_domain_label = domain_labels[0]
other_domain_labels = domain_labels[1:]
wildcard_label = valid_domain_labels[0]
other_valid_domain_labels = valid_domain_labels[1:]
if (other_domain_labels != other_valid_domain_labels):
return False
if (wildcard_label == u'*'):
return True
wildcard_regex = re.compile(((u'^' + wildcard_label.replace(u'*', u'.*')) + u'$'))
if wildcard_regex.match(first_domain_label):
return True
return False
|
'Creates an ECPoint object from the X and Y integer coordinates of the
point
:param x:
The X coordinate, as an integer
:param y:
The Y coordinate, as an integer
:return:
An ECPoint object'
| @classmethod
def from_coords(cls, x, y):
| x_bytes = int(math.ceil((math.log(x, 2) / 8.0)))
y_bytes = int(math.ceil((math.log(y, 2) / 8.0)))
num_bytes = max(x_bytes, y_bytes)
byte_string = '\x04'
byte_string += int_to_bytes(x, width=num_bytes)
byte_string += int_to_bytes(y, width=num_bytes)
return cls(byte_string)
|
'Returns the X and Y coordinates for this EC point, as native Python
integers
:return:
A 2-element tuple containing integers (X, Y)'
| def to_coords(self):
| data = self.native
first_byte = data[0:1]
if (first_byte == '\x04'):
remaining = data[1:]
field_len = (len(remaining) // 2)
x = int_from_bytes(remaining[0:field_len])
y = int_from_bytes(remaining[field_len:])
return (x, y)
if (first_byte not in set(['\x02', '\x03'])):
raise ValueError(unwrap(u'\n Invalid EC public key - first byte is incorrect\n '))
raise ValueError(unwrap(u'\n Compressed representations of EC public keys are not supported due\n to patent US6252960\n '))
|
'Wraps a private key in a PrivateKeyInfo structure
:param private_key:
A byte string or Asn1Value object of the private key
:param algorithm:
A unicode string of "rsa", "dsa" or "ec"
:return:
A PrivateKeyInfo object'
| @classmethod
def wrap(cls, private_key, algorithm):
| if ((not isinstance(private_key, byte_cls)) and (not isinstance(private_key, Asn1Value))):
raise TypeError(unwrap(u'\n private_key must be a byte string or Asn1Value, not %s\n ', type_name(private_key)))
if (algorithm == u'rsa'):
if (not isinstance(private_key, RSAPrivateKey)):
private_key = RSAPrivateKey.load(private_key)
params = Null()
elif (algorithm == u'dsa'):
if (not isinstance(private_key, DSAPrivateKey)):
private_key = DSAPrivateKey.load(private_key)
params = DSAParams()
params[u'p'] = private_key[u'p']
params[u'q'] = private_key[u'q']
params[u'g'] = private_key[u'g']
public_key = private_key[u'public_key']
private_key = private_key[u'private_key']
elif (algorithm == u'ec'):
if (not isinstance(private_key, ECPrivateKey)):
private_key = ECPrivateKey.load(private_key)
else:
private_key = private_key.copy()
params = private_key[u'parameters']
del private_key[u'parameters']
else:
raise ValueError(unwrap(u'\n algorithm must be one of "rsa", "dsa", "ec", not %s\n ', repr(algorithm)))
private_key_algo = PrivateKeyAlgorithm()
private_key_algo[u'algorithm'] = PrivateKeyAlgorithmId(algorithm)
private_key_algo[u'parameters'] = params
container = cls()
container._algorithm = algorithm
container[u'version'] = Integer(0)
container[u'private_key_algorithm'] = private_key_algo
container[u'private_key'] = private_key
if (algorithm == u'dsa'):
container._public_key = public_key
return container
|
'Computes the public key corresponding to the current private key.
:return:
For RSA keys, an RSAPublicKey object. For DSA keys, an Integer
object. For EC keys, an ECPointBitString.'
| def _compute_public_key(self):
| if (self.algorithm == u'dsa'):
params = self[u'private_key_algorithm'][u'parameters']
return Integer(pow(params[u'g'].native, self[u'private_key'].parsed.native, params[u'p'].native))
if (self.algorithm == u'rsa'):
key = self[u'private_key'].parsed
return RSAPublicKey({u'modulus': key[u'modulus'], u'public_exponent': key[u'public_exponent']})
if (self.algorithm == u'ec'):
(curve_type, details) = self.curve
if (curve_type == u'implicit_ca'):
raise ValueError(unwrap(u'\n Unable to compute public key for EC key using Implicit CA\n parameters\n '))
if (curve_type == u'specified'):
if (details[u'field_id'][u'field_type'] == u'characteristic_two_field'):
raise ValueError(unwrap(u'\n Unable to compute public key for EC key over a\n characteristic two field\n '))
curve = PrimeCurve(details[u'field_id'][u'parameters'], int_from_bytes(details[u'curve'][u'a']), int_from_bytes(details[u'curve'][u'b']))
(base_x, base_y) = self[u'private_key_algorithm'][u'parameters'].chosen[u'base'].to_coords()
base_point = PrimePoint(curve, base_x, base_y)
elif (curve_type == u'named'):
if (details not in (u'secp192r1', u'secp224r1', u'secp256r1', u'secp384r1', u'secp521r1')):
raise ValueError(unwrap(u'\n Unable to compute public key for EC named curve %s,\n parameters not currently included\n ', details))
base_point = {u'secp192r1': SECP192R1_BASE_POINT, u'secp224r1': SECP224R1_BASE_POINT, u'secp256r1': SECP256R1_BASE_POINT, u'secp384r1': SECP384R1_BASE_POINT, u'secp521r1': SECP521R1_BASE_POINT}[details]
public_point = (base_point * self[u'private_key'].parsed[u'private_key'].native)
return ECPointBitString.from_coords(public_point.x, public_point.y)
|
'Unwraps the private key into an RSAPrivateKey, DSAPrivateKey or
ECPrivateKey object
:return:
An RSAPrivateKey, DSAPrivateKey or ECPrivateKey object'
| def unwrap(self):
| if (self.algorithm == u'rsa'):
return self[u'private_key'].parsed
if (self.algorithm == u'dsa'):
params = self[u'private_key_algorithm'][u'parameters']
return DSAPrivateKey({u'version': 0, u'p': params[u'p'], u'q': params[u'q'], u'g': params[u'g'], u'public_key': self.public_key, u'private_key': self[u'private_key'].parsed})
if (self.algorithm == u'ec'):
output = self[u'private_key'].parsed
output[u'parameters'] = self[u'private_key_algorithm'][u'parameters']
output[u'public_key'] = self.public_key
return output
|
'Returns information about the curve used for an EC key
:raises:
ValueError - when the key is not an EC key
:return:
A two-element tuple, with the first element being a unicode string
of "implicit_ca", "specified" or "named". If the first element is
"implicit_ca", the second is None. If "specified", the second is
an OrderedDict that is the native version of SpecifiedECDomain. If
"named", the second is a unicode string of the curve name.'
| @property
def curve(self):
| if (self.algorithm != u'ec'):
raise ValueError(unwrap(u'\n Only EC keys have a curve, this key is %s\n ', self.algorithm.upper()))
params = self[u'private_key_algorithm'][u'parameters']
chosen = params.chosen
if (params.name == u'implicit_ca'):
value = None
else:
value = chosen.native
return (params.name, value)
|
'Returns the name of the family of hash algorithms used to generate a
DSA key
:raises:
ValueError - when the key is not a DSA key
:return:
A unicode string of "sha1" or "sha2"'
| @property
def hash_algo(self):
| if (self.algorithm != u'dsa'):
raise ValueError(unwrap(u'\n Only DSA keys are generated using a hash algorithm, this key is\n %s\n ', self.algorithm.upper()))
byte_len = (math.log(self[u'private_key_algorithm'][u'parameters'][u'q'].native, 2) / 8)
return (u'sha1' if (byte_len <= 20) else u'sha2')
|
':return:
A unicode string of "rsa", "dsa" or "ec"'
| @property
def algorithm(self):
| if (self._algorithm is None):
self._algorithm = self[u'private_key_algorithm'][u'algorithm'].native
return self._algorithm
|
':return:
The bit size of the private key, as an integer'
| @property
def bit_size(self):
| if (self._bit_size is None):
if (self.algorithm == u'rsa'):
prime = self[u'private_key'].parsed[u'modulus'].native
elif (self.algorithm == u'dsa'):
prime = self[u'private_key_algorithm'][u'parameters'][u'p'].native
elif (self.algorithm == u'ec'):
prime = self[u'private_key'].parsed[u'private_key'].native
self._bit_size = int(math.ceil(math.log(prime, 2)))
modulus = (self._bit_size % 8)
if (modulus != 0):
self._bit_size += (8 - modulus)
return self._bit_size
|
':return:
The byte size of the private key, as an integer'
| @property
def byte_size(self):
| return int(math.ceil((self.bit_size / 8)))
|
':return:
If an RSA key, an RSAPublicKey object. If a DSA key, an Integer
object. If an EC key, an ECPointBitString object.'
| @property
def public_key(self):
| if (self._public_key is None):
if (self.algorithm == u'ec'):
key = self[u'private_key'].parsed
if key[u'public_key']:
self._public_key = key[u'public_key'].untag()
else:
self._public_key = self._compute_public_key()
else:
self._public_key = self._compute_public_key()
return self._public_key
|
':return:
A PublicKeyInfo object derived from this private key.'
| @property
def public_key_info(self):
| return PublicKeyInfo({u'algorithm': {u'algorithm': self.algorithm, u'parameters': self[u'private_key_algorithm'][u'parameters']}, u'public_key': self.public_key})
|
'Creates a fingerprint that can be compared with a public key to see if
the two form a pair.
This fingerprint is not compatiable with fingerprints generated by any
other software.
:return:
A byte string that is a sha256 hash of selected components (based
on the key type)'
| @property
def fingerprint(self):
| if (self._fingerprint is None):
params = self[u'private_key_algorithm'][u'parameters']
key = self[u'private_key'].parsed
if (self.algorithm == u'rsa'):
to_hash = (u'%d:%d' % (key[u'modulus'].native, key[u'public_exponent'].native))
elif (self.algorithm == u'dsa'):
public_key = self.public_key
to_hash = (u'%d:%d:%d:%d' % (params[u'p'].native, params[u'q'].native, params[u'g'].native, public_key.native))
elif (self.algorithm == u'ec'):
public_key = key[u'public_key'].native
if (public_key is None):
public_key = self.public_key.native
if (params.name == u'named'):
to_hash = (u'%s:' % params.chosen.native)
to_hash = to_hash.encode(u'utf-8')
to_hash += public_key
elif (params.name == u'implicit_ca'):
to_hash = public_key
elif (params.name == u'specified'):
to_hash = (u'%s:' % params.chosen[u'field_id'][u'parameters'].native)
to_hash = to_hash.encode(u'utf-8')
to_hash += (':' + params.chosen[u'curve'][u'a'].native)
to_hash += (':' + params.chosen[u'curve'][u'b'].native)
to_hash += public_key
if isinstance(to_hash, str_cls):
to_hash = to_hash.encode(u'utf-8')
self._fingerprint = hashlib.sha256(to_hash).digest()
return self._fingerprint
|
'Wraps a public key in a PublicKeyInfo structure
:param public_key:
A byte string or Asn1Value object of the public key
:param algorithm:
A unicode string of "rsa"
:return:
A PublicKeyInfo object'
| @classmethod
def wrap(cls, public_key, algorithm):
| if ((not isinstance(public_key, byte_cls)) and (not isinstance(public_key, Asn1Value))):
raise TypeError(unwrap(u'\n public_key must be a byte string or Asn1Value, not %s\n ', type_name(public_key)))
if (algorithm != u'rsa'):
raise ValueError(unwrap(u'\n algorithm must "rsa", not %s\n ', repr(algorithm)))
algo = PublicKeyAlgorithm()
algo[u'algorithm'] = PublicKeyAlgorithmId(algorithm)
algo[u'parameters'] = Null()
container = cls()
container[u'algorithm'] = algo
if isinstance(public_key, Asn1Value):
public_key = public_key.untag().dump()
container[u'public_key'] = ParsableOctetBitString(public_key)
return container
|
'Unwraps an RSA public key into an RSAPublicKey object. Does not support
DSA or EC public keys since they do not have an unwrapped form.
:return:
An RSAPublicKey object'
| def unwrap(self):
| if (self.algorithm == u'rsa'):
return self[u'public_key'].parsed
key_type = self.algorithm.upper()
a_an = (u'an' if (key_type == u'EC') else u'a')
raise ValueError(unwrap(u'\n Only RSA public keys may be unwrapped - this key is %s %s public\n key\n ', a_an, key_type))
|
'Returns information about the curve used for an EC key
:raises:
ValueError - when the key is not an EC key
:return:
A two-element tuple, with the first element being a unicode string
of "implicit_ca", "specified" or "named". If the first element is
"implicit_ca", the second is None. If "specified", the second is
an OrderedDict that is the native version of SpecifiedECDomain. If
"named", the second is a unicode string of the curve name.'
| @property
def curve(self):
| if (self.algorithm != u'ec'):
raise ValueError(unwrap(u'\n Only EC keys have a curve, this key is %s\n ', self.algorithm.upper()))
params = self[u'algorithm'][u'parameters']
chosen = params.chosen
if (params.name == u'implicit_ca'):
value = None
else:
value = chosen.native
return (params.name, value)
|
'Returns the name of the family of hash algorithms used to generate a
DSA key
:raises:
ValueError - when the key is not a DSA key
:return:
A unicode string of "sha1" or "sha2" or None if no parameters are
present'
| @property
def hash_algo(self):
| if (self.algorithm != u'dsa'):
raise ValueError(unwrap(u'\n Only DSA keys are generated using a hash algorithm, this key is\n %s\n ', self.algorithm.upper()))
parameters = self[u'algorithm'][u'parameters']
if (parameters.native is None):
return None
byte_len = (math.log(parameters[u'q'].native, 2) / 8)
return (u'sha1' if (byte_len <= 20) else u'sha2')
|
':return:
A unicode string of "rsa", "dsa" or "ec"'
| @property
def algorithm(self):
| if (self._algorithm is None):
self._algorithm = self[u'algorithm'][u'algorithm'].native
return self._algorithm
|
':return:
The bit size of the public key, as an integer'
| @property
def bit_size(self):
| if (self._bit_size is None):
if (self.algorithm == u'ec'):
self._bit_size = (((len(self[u'public_key'].native) - 1) / 2) * 8)
else:
if (self.algorithm == u'rsa'):
prime = self[u'public_key'].parsed[u'modulus'].native
elif (self.algorithm == u'dsa'):
prime = self[u'algorithm'][u'parameters'][u'p'].native
self._bit_size = int(math.ceil(math.log(prime, 2)))
modulus = (self._bit_size % 8)
if (modulus != 0):
self._bit_size += (8 - modulus)
return self._bit_size
|
':return:
The byte size of the public key, as an integer'
| @property
def byte_size(self):
| return int(math.ceil((self.bit_size / 8)))
|
':return:
The SHA1 hash of the DER-encoded bytes of this public key info'
| @property
def sha1(self):
| if (self._sha1 is None):
self._sha1 = hashlib.sha1(byte_cls(self[u'public_key'])).digest()
return self._sha1
|
':return:
The SHA-256 hash of the DER-encoded bytes of this public key info'
| @property
def sha256(self):
| if (self._sha256 is None):
self._sha256 = hashlib.sha256(byte_cls(self[u'public_key'])).digest()
return self._sha256
|
'Creates a fingerprint that can be compared with a private key to see if
the two form a pair.
This fingerprint is not compatiable with fingerprints generated by any
other software.
:return:
A byte string that is a sha256 hash of selected components (based
on the key type)'
| @property
def fingerprint(self):
| if (self._fingerprint is None):
key_type = self[u'algorithm'][u'algorithm'].native
params = self[u'algorithm'][u'parameters']
if (key_type == u'rsa'):
key = self[u'public_key'].parsed
to_hash = (u'%d:%d' % (key[u'modulus'].native, key[u'public_exponent'].native))
elif (key_type == u'dsa'):
key = self[u'public_key'].parsed
to_hash = (u'%d:%d:%d:%d' % (params[u'p'].native, params[u'q'].native, params[u'g'].native, key.native))
elif (key_type == u'ec'):
key = self[u'public_key']
if (params.name == u'named'):
to_hash = (u'%s:' % params.chosen.native)
to_hash = to_hash.encode(u'utf-8')
to_hash += key.native
elif (params.name == u'implicit_ca'):
to_hash = key.native
elif (params.name == u'specified'):
to_hash = (u'%s:' % params.chosen[u'field_id'][u'parameters'].native)
to_hash = to_hash.encode(u'utf-8')
to_hash += (':' + params.chosen[u'curve'][u'a'].native)
to_hash += (':' + params.chosen[u'curve'][u'b'].native)
to_hash += key.native
if isinstance(to_hash, str_cls):
to_hash = to_hash.encode(u'utf-8')
self._fingerprint = hashlib.sha256(to_hash).digest()
return self._fingerprint
|
'The curve of points satisfying y^2 = x^3 + a*x + b (mod p)
:param p:
The prime number as an integer
:param a:
The component a as an integer
:param b:
The component b as an integer'
| def __init__(self, p, a, b):
| self.p = p
self.a = a
self.b = b
|
':param point:
A Point object
:return:
Boolean if the point is on this curve'
| def contains(self, point):
| y2 = (point.y * point.y)
x3 = ((point.x * point.x) * point.x)
return (((y2 - ((x3 + (self.a * point.x)) + self.b)) % self.p) == 0)
|
':param curve:
A PrimeCurve object
:param x:
The x coordinate of the point as an integer
:param y:
The y coordinate of the point as an integer
:param order:
The order of the point, as an integer - optional'
| def __init__(self, curve, x, y, order=None):
| self.curve = curve
self.x = x
self.y = y
self.order = order
if self.curve:
if (not self.curve.contains(self)):
raise ValueError(u'Invalid EC point')
if self.order:
if ((self * self.order) != INFINITY):
raise ValueError(u'Invalid EC point')
|
':param other:
A PrimePoint object
:return:
0 if identical, 1 otherwise'
| def __cmp__(self, other):
| if ((self.curve == other.curve) and (self.x == other.x) and (self.y == other.y)):
return 0
else:
return 1
|
':param other:
A PrimePoint object
:return:
A PrimePoint object'
| def __add__(self, other):
| if (other == INFINITY):
return self
if (self == INFINITY):
return other
assert (self.curve == other.curve)
if (self.x == other.x):
if (((self.y + other.y) % self.curve.p) == 0):
return INFINITY
else:
return self.double()
p = self.curve.p
l = (((other.y - self.y) * inverse_mod((other.x - self.x), p)) % p)
x3 = ((((l * l) - self.x) - other.x) % p)
y3 = (((l * (self.x - x3)) - self.y) % p)
return PrimePoint(self.curve, x3, y3)
|
':param other:
An integer to multiple the Point by
:return:
A PrimePoint object'
| def __mul__(self, other):
| def leftmost_bit(x):
assert (x > 0)
result = 1
while (result <= x):
result = (2 * result)
return (result // 2)
e = other
if self.order:
e = (e % self.order)
if (e == 0):
return INFINITY
if (self == INFINITY):
return INFINITY
assert (e > 0)
e3 = (3 * e)
negative_self = PrimePoint(self.curve, self.x, (- self.y), self.order)
i = (leftmost_bit(e3) // 2)
result = self
while (i > 1):
result = result.double()
if (((e3 & i) != 0) and ((e & i) == 0)):
result = (result + self)
if (((e3 & i) == 0) and ((e & i) != 0)):
result = (result + negative_self)
i = (i // 2)
return result
|
':param other:
An integer to multiple the Point by
:return:
A PrimePoint object'
| def __rmul__(self, other):
| return (self * other)
|
':return:
A PrimePoint object that is twice this point'
| def double(self):
| p = self.curve.p
a = self.curve.a
l = (((((3 * self.x) * self.x) + a) * inverse_mod((2 * self.y), p)) % p)
x3 = (((l * l) - (2 * self.x)) % p)
y3 = (((l * (self.x - x3)) - self.y) % p)
return PrimePoint(self.curve, x3, y3)
|
'Register a function to convert a core foundation data type into its
equivalent in python
:param type_id:
The CFTypeId for the type
:param callback:
A callback to pass the CFType object to'
| @classmethod
def register_native_mapping(cls, type_id, callback):
| cls._native_map[int(type_id)] = callback
|
'Converts a CFNumber object to a python float or integer
:param value:
The CFNumber object
:return:
A python number (float or integer)'
| @staticmethod
def cf_number_to_number(value):
| type_ = CoreFoundation.CFNumberGetType(_cast_pointer_p(value))
c_type = {1: c_byte, 2: ctypes.c_short, 3: ctypes.c_int32, 4: ctypes.c_int64, 5: ctypes.c_float, 6: ctypes.c_double, 7: c_byte, 8: ctypes.c_short, 9: ctypes.c_int, 10: c_long, 11: ctypes.c_longlong, 12: ctypes.c_float, 13: ctypes.c_double, 14: c_long, 15: ctypes.c_int, 16: ctypes.c_double}[type_]
output = c_type(0)
CoreFoundation.CFNumberGetValue(_cast_pointer_p(value), type_, byref(output))
return output.value
|
'Converts a CFDictionary object into a python dictionary
:param dictionary:
The CFDictionary to convert
:return:
A python dict'
| @staticmethod
def cf_dictionary_to_dict(dictionary):
| dict_length = CoreFoundation.CFDictionaryGetCount(dictionary)
keys = (CFTypeRef * dict_length)()
values = (CFTypeRef * dict_length)()
CoreFoundation.CFDictionaryGetKeysAndValues(dictionary, _cast_pointer_p(keys), _cast_pointer_p(values))
output = {}
for index in range(0, dict_length):
output[CFHelpers.native(keys[index])] = CFHelpers.native(values[index])
return output
|
'Converts a CF* object into its python equivalent
:param value:
The CF* object to convert
:return:
The native python object'
| @classmethod
def native(cls, value):
| type_id = CoreFoundation.CFGetTypeID(value)
if (type_id in cls._native_map):
return cls._native_map[type_id](value)
else:
return value
|
'Creates a python unicode string from a CFString object
:param value:
The CFString to convert
:return:
A python unicode string'
| @staticmethod
def cf_string_to_unicode(value):
| string = CoreFoundation.CFStringGetCStringPtr(_cast_pointer_p(value), kCFStringEncodingUTF8)
if (string is None):
buffer = buffer_from_bytes(1024)
result = CoreFoundation.CFStringGetCString(_cast_pointer_p(value), buffer, 1024, kCFStringEncodingUTF8)
if (not result):
raise OSError(u'Error copying C string from CFStringRef')
string = byte_string_from_buffer(buffer)
if (string is not None):
string = string.decode(u'utf-8')
return string
|
'Creates a CFStringRef object from a unicode string
:param string:
The unicode string to create the CFString object from
:return:
A CFStringRef'
| @staticmethod
def cf_string_from_unicode(string):
| return CoreFoundation.CFStringCreateWithCString(CoreFoundation.kCFAllocatorDefault, string.encode(u'utf-8'), kCFStringEncodingUTF8)
|
'Extracts a bytestring from a CFData object
:param value:
A CFData object
:return:
A byte string'
| @staticmethod
def cf_data_to_bytes(value):
| start = CoreFoundation.CFDataGetBytePtr(value)
num_bytes = CoreFoundation.CFDataGetLength(value)
return string_at(start, num_bytes)
|
'Creates a CFDataRef object from a byte string
:param bytes_:
The data to create the CFData object from
:return:
A CFDataRef'
| @staticmethod
def cf_data_from_bytes(bytes_):
| return CoreFoundation.CFDataCreate(CoreFoundation.kCFAllocatorDefault, bytes_, len(bytes_))
|
'Creates a CFDictionaryRef object from a list of 2-element tuples
representing the key and value. Each key should be a CFStringRef and each
value some sort of CF* type.
:param pairs:
A list of 2-element tuples
:return:
A CFDictionaryRef'
| @staticmethod
def cf_dictionary_from_pairs(pairs):
| length = len(pairs)
keys = []
values = []
for pair in pairs:
(key, value) = pair
keys.append(key)
values.append(value)
keys = (CFStringRef * length)(*keys)
values = (CFTypeRef * length)(*values)
return CoreFoundation.CFDictionaryCreate(CoreFoundation.kCFAllocatorDefault, _cast_pointer_p(byref(keys)), _cast_pointer_p(byref(values)), length, kCFTypeDictionaryKeyCallBacks, kCFTypeDictionaryValueCallBacks)
|
'Creates a CFArrayRef object from a list of CF* type objects.
:param values:
A list of CF* type object
:return:
A CFArrayRef'
| @staticmethod
def cf_array_from_list(values):
| length = len(values)
values = (CFTypeRef * length)(*values)
return CoreFoundation.CFArrayCreate(CoreFoundation.kCFAllocatorDefault, _cast_pointer_p(byref(values)), length, kCFTypeArrayCallBacks)
|
'Creates a CFNumber object from an integer
:param integer:
The integer to create the CFNumber for
:return:
A CFNumber'
| @staticmethod
def cf_number_from_integer(integer):
| integer_as_long = c_long(integer)
return CoreFoundation.CFNumberCreate(CoreFoundation.kCFAllocatorDefault, kCFNumberCFIndexType, byref(integer_as_long))
|
'Generate the tags URL for a GitHub repo if the value passed is a GitHub
repository URL
:param repo:
The repository URL
:return:
The tags URL if repo was a GitHub repo, otherwise False'
| def make_tags_url(self, repo):
| match = re.match('https?://github.com/([^/]+/[^/]+)/?$', repo)
if (not match):
return False
return ('https://github.com/%s/tags' % match.group(1))
|
'Generate the branch URL for a GitHub repo if the value passed is a GitHub
repository URL
:param repo:
The repository URL
:param branch:
The branch name
:return:
The branch URL if repo was a GitHub repo, otherwise False'
| def make_branch_url(self, repo, branch):
| match = re.match('https?://github.com/([^/]+/[^/]+)/?$', repo)
if (not match):
return False
return ('https://github.com/%s/tree/%s' % (match.group(1), quote(branch)))
|
'Retrieve information about downloading a package
:param url:
The URL of the repository, in one of the forms:
https://github.com/{user}/{repo}
https://github.com/{user}/{repo}/tree/{branch}
https://github.com/{user}/{repo}/tags
If the last option, grabs the info from the newest
tag that is a valid semver version.
:param tag_prefix:
If the URL is a tags URL, only match tags that have this prefix
:raises:
DownloaderException: when there is an error downloading
ClientException: when there is an error parsing the response
:return:
None if no match, False if no commits, or a list of dicts with the
following keys:
`version` - the version number of the download
`url` - the download URL of a zip file of the package
`date` - the ISO-8601 timestamp string when the version was published'
| def download_info(self, url, tag_prefix=None):
| tags_match = re.match('https?://github.com/([^/]+/[^/]+)/tags/?$', url)
version = None
url_pattern = 'https://codeload.github.com/%s/zip/%s'
output = []
if tags_match:
user_repo = tags_match.group(1)
tags_url = self._make_api_url(user_repo, '/tags?per_page=100')
tags_list = self.fetch_json(tags_url)
tags = [tag['name'] for tag in tags_list]
tag_info = version_process(tags, tag_prefix)
tag_info = version_sort(tag_info, reverse=True)
if (not tag_info):
return False
used_versions = {}
for info in tag_info:
version = info['version']
if (version in used_versions):
continue
tag = (info['prefix'] + version)
output.append({'url': (url_pattern % (user_repo, tag)), 'commit': tag, 'version': version})
used_versions[version] = True
else:
(user_repo, commit) = self._user_repo_branch(url)
if (not user_repo):
return user_repo
output.append({'url': (url_pattern % (user_repo, commit)), 'commit': commit})
for release in output:
query_string = urlencode({'sha': release['commit'], 'per_page': 1})
commit_url = self._make_api_url(user_repo, ('/commits?%s' % query_string))
commit_info = self.fetch_json(commit_url)
timestamp = commit_info[0]['commit']['committer']['date'][0:19].replace('T', ' ')
if ('version' not in release):
release['version'] = re.sub('[\\-: ]', '.', timestamp)
release['date'] = timestamp
del release['commit']
return output
|
'Retrieve general information about a repository
:param url:
The URL to the repository, in one of the forms:
https://github.com/{user}/{repo}
https://github.com/{user}/{repo}/tree/{branch}
:raises:
DownloaderException: when there is an error downloading
ClientException: when there is an error parsing the response
:return:
None if no match, or a dict with the following keys:
`name`
`description`
`homepage` - URL of the homepage
`author`
`readme` - URL of the readme
`issues` - URL of bug tracker
`donate` - URL of a donate page'
| def repo_info(self, url):
| (user_repo, branch) = self._user_repo_branch(url)
if (not user_repo):
return user_repo
api_url = self._make_api_url(user_repo)
info = self.fetch_json(api_url)
output = self._extract_repo_info(info)
output['readme'] = None
readme_info = self._readme_info(user_repo, branch)
if (not readme_info):
return output
output['readme'] = ('https://raw.githubusercontent.com/%s/%s/%s' % (user_repo, branch, readme_info['path']))
return output
|
'Retrieve general information about all repositories that are
part of a user/organization.
:param url:
The URL to the user/organization, in the following form:
https://github.com/{user}
:raises:
DownloaderException: when there is an error downloading
ClientException: when there is an error parsing the response
:return:
None if no match, or am list of dicts with the following keys:
`name`
`description`
`homepage` - URL of the homepage
`author`
`readme` - URL of the readme
`issues` - URL of bug tracker
`donate` - URL of a donate page'
| def user_info(self, url):
| user_match = re.match('https?://github.com/([^/]+)/?$', url)
if (user_match is None):
return None
user = user_match.group(1)
api_url = ('https://api.github.com/users/%s/repos' % user)
repos_info = self.fetch_json(api_url)
output = []
for info in repos_info:
user_repo = ('%s/%s' % (user, info['name']))
branch = 'master'
repo_output = self._extract_repo_info(info)
repo_output['readme'] = None
readme_info = self._readme_info(user_repo, branch)
if readme_info:
repo_output['readme'] = ('https://raw.githubusercontent.com/%s/%s/%s' % (user_repo, branch, readme_info['path']))
output.append(repo_output)
return output
|
'Extracts information about a repository from the API result
:param result:
A dict representing the data returned from the GitHub API
:return:
A dict with the following keys:
`name`
`description`
`homepage` - URL of the homepage
`author`
`issues` - URL of bug tracker
`donate` - URL of a donate page'
| def _extract_repo_info(self, result):
| issues_url = (u'https://github.com/%s/%s/issues' % (result['owner']['login'], result['name']))
return {'name': result['name'], 'description': (result['description'] or 'No description provided'), 'homepage': (result['homepage'] or result['html_url']), 'author': result['owner']['login'], 'issues': (issues_url if result['has_issues'] else None), 'donate': None}
|
'Generate a URL for the BitBucket API
:param user_repo:
The user/repo of the repository
:param suffix:
The extra API path info to add to the URL
:return:
The API URL'
| def _make_api_url(self, user_repo, suffix=''):
| return ('https://api.github.com/repos/%s%s' % (user_repo, suffix))
|
'Fetches the raw GitHub API information about a readme
:param user_repo:
The user/repo of the repository
:param branch:
The branch to pull the readme from
:param prefer_cached:
If a cached version of the info should be returned instead of making a new HTTP request
:raises:
DownloaderException: when there is an error downloading
ClientException: when there is an error parsing the response
:return:
A dict containing all of the info from the GitHub API, or None if no readme exists'
| def _readme_info(self, user_repo, branch, prefer_cached=False):
| query_string = urlencode({'ref': branch})
readme_url = self._make_api_url(user_repo, ('/readme?%s' % query_string))
try:
return self.fetch_json(readme_url, prefer_cached)
except DownloaderException as e:
if (str_cls(e).find('HTTP error 404') != (-1)):
return None
raise
|
'Extract the username/repo and branch name from the URL
:param url:
The URL to extract the info from, in one of the forms:
https://github.com/{user}/{repo}
https://github.com/{user}/{repo}/tree/{branch}
:return:
A tuple of (user/repo, branch name) or (None, None) if no match'
| def _user_repo_branch(self, url):
| branch = 'master'
branch_match = re.match('https?://github.com/[^/]+/[^/]+/tree/([^/]+)/?$', url)
if (branch_match is not None):
branch = branch_match.group(1)
repo_match = re.match('https?://github.com/([^/]+/[^/]+)($|/.*$)', url)
if (repo_match is None):
return (None, None)
user_repo = repo_match.group(1)
return (user_repo, branch)
|
'Generate the tags URL for a BitBucket repo if the value passed is a BitBucket
repository URL
:param repo:
The repository URL
:return:
The tags URL if repo was a BitBucket repo, otherwise False'
| def make_tags_url(self, repo):
| match = re.match('https?://bitbucket.org/([^/]+/[^/]+)/?$', repo)
if (not match):
return False
return ('https://bitbucket.org/%s#tags' % match.group(1))
|
'Generate the branch URL for a BitBucket repo if the value passed is a BitBucket
repository URL
:param repo:
The repository URL
:param branch:
The branch name
:return:
The branch URL if repo was a BitBucket repo, otherwise False'
| def make_branch_url(self, repo, branch):
| match = re.match('https?://bitbucket.org/([^/]+/[^/]+)/?$', repo)
if (not match):
return False
return ('https://bitbucket.org/%s/src/%s' % (match.group(1), quote(branch)))
|
'Retrieve information about downloading a package
:param url:
The URL of the repository, in one of the forms:
https://bitbucket.org/{user}/{repo}
https://bitbucket.org/{user}/{repo}/src/{branch}
https://bitbucket.org/{user}/{repo}/#tags
If the last option, grabs the info from the newest
tag that is a valid semver version.
:param tag_prefix:
If the URL is a tags URL, only match tags that have this prefix
:raises:
DownloaderException: when there is an error downloading
ClientException: when there is an error parsing the response
:return:
None if no match, False if no commit, or a list of dicts with the
following keys:
`version` - the version number of the download
`url` - the download URL of a zip file of the package
`date` - the ISO-8601 timestamp string when the version was published'
| def download_info(self, url, tag_prefix=None):
| tags_match = re.match('https?://bitbucket.org/([^/]+/[^#/]+)/?#tags$', url)
version = None
url_pattern = 'https://bitbucket.org/%s/get/%s.zip'
output = []
if tags_match:
user_repo = tags_match.group(1)
tags_url = self._make_api_url(user_repo, '/tags')
tags_list = self.fetch_json(tags_url)
tag_info = version_process(tags_list.keys(), tag_prefix)
tag_info = version_sort(tag_info, reverse=True)
if (not tag_info):
return False
used_versions = {}
for info in tag_info:
version = info['version']
if (version in used_versions):
continue
tag = (info['prefix'] + version)
output.append({'url': (url_pattern % (user_repo, tag)), 'commit': tag, 'version': version})
used_versions[version] = True
else:
(user_repo, commit) = self._user_repo_branch(url)
if (not user_repo):
return user_repo
output.append({'url': (url_pattern % (user_repo, commit)), 'commit': commit})
for release in output:
changeset_url = self._make_api_url(user_repo, ('/changesets/%s' % release['commit']))
commit_info = self.fetch_json(changeset_url)
timestamp = commit_info['utctimestamp'][0:19]
if ('version' not in release):
release['version'] = re.sub('[\\-: ]', '.', timestamp)
release['date'] = timestamp
del release['commit']
return output
|
'Retrieve general information about a repository
:param url:
The URL to the repository, in one of the forms:
https://bitbucket.org/{user}/{repo}
https://bitbucket.org/{user}/{repo}/src/{branch}
:raises:
DownloaderException: when there is an error downloading
ClientException: when there is an error parsing the response
:return:
None if no match, or a dict with the following keys:
`name`
`description`
`homepage` - URL of the homepage
`author`
`readme` - URL of the readme
`issues` - URL of bug tracker
`donate` - URL of a donate page'
| def repo_info(self, url):
| (user_repo, branch) = self._user_repo_branch(url)
if (not user_repo):
return user_repo
api_url = self._make_api_url(user_repo)
info = self.fetch_json(api_url)
issues_url = (u'https://bitbucket.org/%s/issues' % user_repo)
return {'name': info['name'], 'description': (info['description'] or 'No description provided'), 'homepage': (info['website'] or url), 'author': info['owner'], 'donate': None, 'readme': self._readme_url(user_repo, branch), 'issues': (issues_url if info['has_issues'] else None)}
|
'Fetch the name of the default branch
:param user_repo:
The user/repo name to get the main branch for
:raises:
DownloaderException: when there is an error downloading
ClientException: when there is an error parsing the response
:return:
The name of the main branch - `master` or `default`'
| def _main_branch_name(self, user_repo):
| main_branch_url = self._make_api_url(user_repo, '/main-branch')
main_branch_info = self.fetch_json(main_branch_url, True)
return main_branch_info['name']
|
'Generate a URL for the BitBucket API
:param user_repo:
The user/repo of the repository
:param suffix:
The extra API path info to add to the URL
:return:
The API URL'
| def _make_api_url(self, user_repo, suffix=''):
| return ('https://api.bitbucket.org/1.0/repositories/%s%s' % (user_repo, suffix))
|
'Parse the root directory listing for the repo and return the URL
to any file that looks like a readme
:param user_repo:
The user/repo string
:param branch:
The branch to fetch the readme from
:param prefer_cached:
If a cached directory listing should be used instead of a new HTTP request
:raises:
DownloaderException: when there is an error downloading
ClientException: when there is an error parsing the response
:return:
The URL to the readme file, or None'
| def _readme_url(self, user_repo, branch, prefer_cached=False):
| listing_url = self._make_api_url(user_repo, ('/src/%s/' % branch))
root_dir_info = self.fetch_json(listing_url, prefer_cached)
for entry in root_dir_info['files']:
if (entry['path'].lower() in _readme_filenames):
return ('https://bitbucket.org/%s/raw/%s/%s' % (user_repo, branch, entry['path']))
return None
|
'Extract the username/repo and branch name from the URL
:param url:
The URL to extract the info from, in one of the forms:
https://bitbucket.org/{user}/{repo}
https://bitbucket.org/{user}/{repo}/src/{branch}
:raises:
DownloaderException: when there is an error downloading
ClientException: when there is an error parsing the response
:return:
A tuple of (user/repo, branch name) or (None, None) if not matching'
| def _user_repo_branch(self, url):
| repo_match = re.match('https?://bitbucket.org/([^/]+/[^/]+)/?$', url)
branch_match = re.match('https?://bitbucket.org/([^/]+/[^/]+)/src/([^/]+)/?$', url)
if repo_match:
user_repo = repo_match.group(1)
branch = self._main_branch_name(user_repo)
elif branch_match:
user_repo = branch_match.group(1)
branch = branch_match.group(2)
else:
return (None, None)
return (user_repo, branch)
|
'Retrieve the readme and info about it
:param url:
The URL of the readme file
:raises:
DownloaderException: if there is an error downloading the readme
ClientException: if there is an error parsing the response
:return:
A dict with the following keys:
`filename`
`format` - `markdown`, `textile`, `creole`, `rst` or `txt`
`contents` - contents of the readme as str/unicode'
| def readme_info(self, url):
| contents = None
github_match = re.match('https://raw\\.github(?:usercontent)?\\.com/([^/]+/[^/]+)/([^/]+)/readme(\\.(md|mkd|mdown|markdown|textile|creole|rst|txt))?$', url, re.I)
if github_match:
user_repo = github_match.group(1)
branch = github_match.group(2)
query_string = urlencode({'ref': branch})
readme_json_url = ('https://api.github.com/repos/%s/readme?%s' % (user_repo, query_string))
try:
info = self.fetch_json(readme_json_url, prefer_cached=True)
contents = base64.b64decode(info['content'])
except ValueError:
pass
if (not contents):
contents = self.fetch(url)
(basename, ext) = os.path.splitext(url)
format = 'txt'
ext = ext.lower()
if (ext in _readme_formats):
format = _readme_formats[ext]
try:
contents = contents.decode('utf-8')
except UnicodeDecodeError:
contents = contents.decode('cp1252', errors='replace')
return {'filename': os.path.basename(url), 'format': format, 'contents': contents}
|
'Retrieves the contents of a URL
:param url:
The URL to download the content from
:param prefer_cached:
If a cached copy of the content is preferred
:return: The bytes/string'
| def fetch(self, url, prefer_cached=False):
| extra_params = self.settings.get('query_string_params')
domain_name = urlparse(url).netloc
if (extra_params and (domain_name in extra_params)):
params = urlencode(extra_params[domain_name])
joiner = ('?%s' if (url.find('?') == (-1)) else '&%s')
url += (joiner % params)
with downloader(url, self.settings) as manager:
content = manager.fetch(url, 'Error downloading repository.', prefer_cached)
return content
|
'Retrieves and parses the JSON from a URL
:param url:
The URL to download the JSON from
:param prefer_cached:
If a cached copy of the JSON is preferred
:return: A dict or list from the JSON'
| def fetch_json(self, url, prefer_cached=False):
| repository_json = self.fetch(url, prefer_cached)
try:
return json.loads(repository_json.decode('utf-8'))
except ValueError:
error_string = (u'Error parsing JSON from URL %s.' % url)
raise ClientException(error_string)
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.