_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q259600 | VCard._process_rfc2425_record | validation | def _process_rfc2425_record(self,data):
"""Parse single RFC2425 record and update attributes of `self`.
:Parameters:
- `data`: the record (probably multiline)
:Types:
- `data`: `unicode`"""
label,value=data.split(":",1)
value=value.replace("\\n","\n").replace("\\N","\n")
psplit=label.lower().split(";")
name=psplit[0]
params=psplit[1:]
if u"." in name:
name=name.split(".",1)[1]
name=name.upper()
if name in (u"X-DESC",u"X-JABBERID"):
name=name[2:]
if not self.components.has_key(name):
return
if params:
params=dict([p.split("=",1) for p in params])
cl,tp=self.components[name]
if tp in ("required","optional"):
if self.content.has_key(name):
raise ValueError("Duplicate %s" % (name,))
try:
self.content[name]=cl(name,value,params)
except Empty:
pass
elif tp=="multi":
if not self.content.has_key(name):
self.content[name]=[]
try:
self.content[name].append(cl(name,value,params))
except Empty:
pass
else:
return | python | {
"resource": ""
} |
q259601 | VCard.rfc2426 | validation | def rfc2426(self):
"""Get the RFC2426 representation of `self`.
:return: the UTF-8 encoded RFC2426 representation.
:returntype: `str`"""
ret="begin:VCARD\r\n"
ret+="version:3.0\r\n"
for _unused, value in self.content.items():
if value is None:
continue
if type(value) is list:
for v in value:
ret+=v.rfc2426()
else:
v=value.rfc2426()
ret+=v
return ret+"end:VCARD\r\n" | python | {
"resource": ""
} |
q259602 | CacheItem.update_state | validation | def update_state(self):
"""Update current status of the item and compute time of the next
state change.
:return: the new state.
:returntype: :std:`datetime`"""
self._lock.acquire()
try:
now = datetime.utcnow()
if self.state == 'new':
self.state = 'fresh'
if self.state == 'fresh':
if now > self.freshness_time:
self.state = 'old'
if self.state == 'old':
if now > self.expire_time:
self.state = 'stale'
if self.state == 'stale':
if now > self.purge_time:
self.state = 'purged'
self.state_value = _state_values[self.state]
return self.state
finally:
self._lock.release() | python | {
"resource": ""
} |
q259603 | CacheFetcher._deactivate | validation | def _deactivate(self):
"""Remove the fetcher from cache and mark it not active."""
self.cache.remove_fetcher(self)
if self.active:
self._deactivated() | python | {
"resource": ""
} |
q259604 | CacheFetcher.got_it | validation | def got_it(self, value, state = "new"):
"""Handle a successfull retrieval and call apriopriate handler.
Should be called when retrieval succeeds.
Do nothing when the fetcher is not active any more (after
one of handlers was already called).
:Parameters:
- `value`: fetched object.
- `state`: initial state of the object.
:Types:
- `value`: any
- `state`: `str`"""
if not self.active:
return
item = CacheItem(self.address, value, self._item_freshness_period,
self._item_expiration_period, self._item_purge_period, state)
self._object_handler(item.address, item.value, item.state)
self.cache.add_item(item)
self._deactivate() | python | {
"resource": ""
} |
q259605 | CacheFetcher.error | validation | def error(self, error_data):
"""Handle a retrieval error and call apriopriate handler.
Should be called when retrieval fails.
Do nothing when the fetcher is not active any more (after
one of handlers was already called).
:Parameters:
- `error_data`: additional information about the error (e.g. `StanzaError` instance).
:Types:
- `error_data`: fetcher dependant
"""
if not self.active:
return
if not self._try_backup_item():
self._error_handler(self.address, error_data)
self.cache.invalidate_object(self.address)
self._deactivate() | python | {
"resource": ""
} |
q259606 | CacheFetcher.timeout | validation | def timeout(self):
"""Handle fetcher timeout and call apriopriate handler.
Is called by the cache object and should _not_ be called by fetcher or
application.
Do nothing when the fetcher is not active any more (after
one of handlers was already called)."""
if not self.active:
return
if not self._try_backup_item():
if self._timeout_handler:
self._timeout_handler(self.address)
else:
self._error_handler(self.address, None)
self.cache.invalidate_object(self.address)
self._deactivate() | python | {
"resource": ""
} |
q259607 | CacheFetcher._try_backup_item | validation | def _try_backup_item(self):
"""Check if a backup item is available in cache and call
the item handler if it is.
:return: `True` if backup item was found.
:returntype: `bool`"""
if not self._backup_state:
return False
item = self.cache.get_item(self.address, self._backup_state)
if item:
self._object_handler(item.address, item.value, item.state)
return True
else:
False | python | {
"resource": ""
} |
q259608 | Cache.add_item | validation | def add_item(self, item):
"""Add an item to the cache.
Item state is updated before adding it (it will not be 'new' any more).
:Parameters:
- `item`: the item to add.
:Types:
- `item`: `CacheItem`
:return: state of the item after addition.
:returntype: `str`
"""
self._lock.acquire()
try:
state = item.update_state()
if state != 'purged':
if len(self._items_list) >= self.max_items:
self.purge_items()
self._items[item.address] = item
self._items_list.append(item)
self._items_list.sort()
return item.state
finally:
self._lock.release() | python | {
"resource": ""
} |
q259609 | Cache.get_item | validation | def get_item(self, address, state = 'fresh'):
"""Get an item from the cache.
:Parameters:
- `address`: its address.
- `state`: the worst state that is acceptable.
:Types:
- `address`: any hashable
- `state`: `str`
:return: the item or `None` if it was not found.
:returntype: `CacheItem`"""
self._lock.acquire()
try:
item = self._items.get(address)
if not item:
return None
self.update_item(item)
if _state_values[state] >= item.state_value:
return item
return None
finally:
self._lock.release() | python | {
"resource": ""
} |
q259610 | Cache.update_item | validation | def update_item(self, item):
"""Update state of an item in the cache.
Update item's state and remove the item from the cache
if its new state is 'purged'
:Parameters:
- `item`: item to update.
:Types:
- `item`: `CacheItem`
:return: new state of the item.
:returntype: `str`"""
self._lock.acquire()
try:
state = item.update_state()
self._items_list.sort()
if item.state == 'purged':
self._purged += 1
if self._purged > 0.25*self.max_items:
self.purge_items()
return state
finally:
self._lock.release() | python | {
"resource": ""
} |
q259611 | Cache.purge_items | validation | def purge_items(self):
"""Remove purged and overlimit items from the cache.
TODO: optimize somehow.
Leave no more than 75% of `self.max_items` items in the cache."""
self._lock.acquire()
try:
il=self._items_list
num_items = len(il)
need_remove = num_items - int(0.75 * self.max_items)
for _unused in range(need_remove):
item=il.pop(0)
try:
del self._items[item.address]
except KeyError:
pass
while il and il[0].update_state()=="purged":
item=il.pop(0)
try:
del self._items[item.address]
except KeyError:
pass
finally:
self._lock.release() | python | {
"resource": ""
} |
q259612 | Cache.remove_fetcher | validation | def remove_fetcher(self, fetcher):
"""Remove a running fetcher from the list of active fetchers.
:Parameters:
- `fetcher`: fetcher instance.
:Types:
- `fetcher`: `CacheFetcher`"""
self._lock.acquire()
try:
for t, f in list(self._active_fetchers):
if f is fetcher:
self._active_fetchers.remove((t, f))
f._deactivated()
return
finally:
self._lock.release() | python | {
"resource": ""
} |
q259613 | Cache.set_fetcher | validation | def set_fetcher(self, fetcher_class):
"""Set the fetcher class.
:Parameters:
- `fetcher_class`: the fetcher class.
:Types:
- `fetcher_class`: `CacheFetcher` based class
"""
self._lock.acquire()
try:
self._fetcher = fetcher_class
finally:
self._lock.release() | python | {
"resource": ""
} |
q259614 | CacheSuite.register_fetcher | validation | def register_fetcher(self, object_class, fetcher_class):
"""Register a fetcher class for an object class.
:Parameters:
- `object_class`: class to be retrieved by the fetcher.
- `fetcher_class`: the fetcher class.
:Types:
- `object_class`: `classobj`
- `fetcher_class`: `CacheFetcher` based class
"""
self._lock.acquire()
try:
cache = self._caches.get(object_class)
if not cache:
cache = Cache(self.max_items, self.default_freshness_period,
self.default_expiration_period, self.default_purge_period)
self._caches[object_class] = cache
cache.set_fetcher(fetcher_class)
finally:
self._lock.release() | python | {
"resource": ""
} |
q259615 | CacheSuite.unregister_fetcher | validation | def unregister_fetcher(self, object_class):
"""Unregister a fetcher class for an object class.
:Parameters:
- `object_class`: class retrieved by the fetcher.
:Types:
- `object_class`: `classobj`
"""
self._lock.acquire()
try:
cache = self._caches.get(object_class)
if not cache:
return
cache.set_fetcher(None)
finally:
self._lock.release() | python | {
"resource": ""
} |
q259616 | _register_client_authenticator | validation | def _register_client_authenticator(klass, name):
"""Add a client authenticator class to `CLIENT_MECHANISMS_D`,
`CLIENT_MECHANISMS` and, optionally, to `SECURE_CLIENT_MECHANISMS`
"""
# pylint: disable-msg=W0212
CLIENT_MECHANISMS_D[name] = klass
items = sorted(CLIENT_MECHANISMS_D.items(), key = _key_func, reverse = True)
CLIENT_MECHANISMS[:] = [k for (k, v) in items ]
SECURE_CLIENT_MECHANISMS[:] = [k for (k, v) in items
if v._pyxmpp_sasl_secure] | python | {
"resource": ""
} |
q259617 | _register_server_authenticator | validation | def _register_server_authenticator(klass, name):
"""Add a client authenticator class to `SERVER_MECHANISMS_D`,
`SERVER_MECHANISMS` and, optionally, to `SECURE_SERVER_MECHANISMS`
"""
# pylint: disable-msg=W0212
SERVER_MECHANISMS_D[name] = klass
items = sorted(SERVER_MECHANISMS_D.items(), key = _key_func, reverse = True)
SERVER_MECHANISMS[:] = [k for (k, v) in items ]
SECURE_SERVER_MECHANISMS[:] = [k for (k, v) in items
if v._pyxmpp_sasl_secure] | python | {
"resource": ""
} |
q259618 | sasl_mechanism | validation | def sasl_mechanism(name, secure, preference = 50):
"""Class decorator generator for `ClientAuthenticator` or
`ServerAuthenticator` subclasses. Adds the class to the pyxmpp.sasl
mechanism registry.
:Parameters:
- `name`: SASL mechanism name
- `secure`: if the mechanims can be considered secure - `True`
if it can be used over plain-text channel
- `preference`: mechanism preference level (the higher the better)
:Types:
- `name`: `unicode`
- `secure`: `bool`
- `preference`: `int`
"""
# pylint: disable-msg=W0212
def decorator(klass):
"""The decorator."""
klass._pyxmpp_sasl_secure = secure
klass._pyxmpp_sasl_preference = preference
if issubclass(klass, ClientAuthenticator):
_register_client_authenticator(klass, name)
elif issubclass(klass, ServerAuthenticator):
_register_server_authenticator(klass, name)
else:
raise TypeError("Not a ClientAuthenticator"
" or ServerAuthenticator class")
return klass
return decorator | python | {
"resource": ""
} |
q259619 | PasswordDatabase.check_password | validation | def check_password(self, username, password, properties):
"""Check the password validity.
Used by plain-text authentication mechanisms.
Default implementation: retrieve a "plain" password for the `username`
and `realm` using `self.get_password` and compare it with the password
provided.
May be overridden e.g. to check the password against some external
authentication mechanism (PAM, LDAP, etc.).
:Parameters:
- `username`: the username for which the password verification is
requested.
- `password`: the password to verify.
- `properties`: mapping with authentication properties (those
provided to the authenticator's ``start()`` method plus some
already obtained via the mechanism).
:Types:
- `username`: `unicode`
- `password`: `unicode`
- `properties`: mapping
:return: `True` if the password is valid.
:returntype: `bool`
"""
logger.debug("check_password{0!r}".format(
(username, password, properties)))
pwd, pwd_format = self.get_password(username,
(u"plain", u"md5:user:realm:password"), properties)
if pwd_format == u"plain":
logger.debug("got plain password: {0!r}".format(pwd))
return pwd is not None and password == pwd
elif pwd_format in (u"md5:user:realm:password"):
logger.debug("got md5:user:realm:password password: {0!r}"
.format(pwd))
realm = properties.get("realm")
if realm is None:
realm = ""
else:
realm = realm.encode("utf-8")
username = username.encode("utf-8")
password = password.encode("utf-8")
# pylint: disable-msg=E1101
urp_hash = hashlib.md5(b"%s:%s:%s").hexdigest()
return urp_hash == pwd
logger.debug("got password in unknown format: {0!r}".format(pwd_format))
return False | python | {
"resource": ""
} |
q259620 | Reply.encode | validation | def encode(self):
"""Base64-encode the data contained in the reply when appropriate.
:return: encoded data.
:returntype: `unicode`
"""
if self.data is None:
return ""
elif not self.data:
return "="
else:
ret = standard_b64encode(self.data)
return ret.decode("us-ascii") | python | {
"resource": ""
} |
q259621 | SessionHandler.handle_authorized | validation | def handle_authorized(self, event):
"""Send session esteblishment request if the feature was advertised by
the server.
"""
stream = event.stream
if not stream:
return
if not stream.initiator:
return
if stream.features is None:
return
element = stream.features.find(SESSION_TAG)
if element is None:
return
logger.debug("Establishing IM session")
stanza = Iq(stanza_type = "set")
payload = XMLPayload(ElementTree.Element(SESSION_TAG))
stanza.set_payload(payload)
self.stanza_processor.set_response_handlers(stanza,
self._session_success,
self._session_error)
stream.send(stanza) | python | {
"resource": ""
} |
q259622 | _decode_asn1_string | validation | def _decode_asn1_string(data):
"""Convert ASN.1 string to a Unicode string.
"""
if isinstance(data, BMPString):
return bytes(data).decode("utf-16-be")
else:
return bytes(data).decode("utf-8") | python | {
"resource": ""
} |
q259623 | CertificateData.display_name | validation | def display_name(self):
"""Get human-readable subject name derived from the SubjectName
or SubjectAltName field.
"""
if self.subject_name:
return u", ".join( [ u", ".join(
[ u"{0}={1}".format(k,v) for k, v in dn_tuple ] )
for dn_tuple in self.subject_name ])
for name_type in ("XmppAddr", "DNS", "SRV"):
names = self.alt_names.get(name_type)
if names:
return names[0]
return u"<unknown>" | python | {
"resource": ""
} |
q259624 | CertificateData.verify_server | validation | def verify_server(self, server_name, srv_type = 'xmpp-client'):
"""Verify certificate for a server.
:Parameters:
- `server_name`: name of the server presenting the cerificate
- `srv_type`: service type requested, as used in the SRV record
:Types:
- `server_name`: `unicode` or `JID`
- `srv_type`: `unicode`
:Return: `True` if the certificate is valid for given name, `False`
otherwise.
"""
server_jid = JID(server_name)
if "XmppAddr" not in self.alt_names and "DNS" not in self.alt_names \
and "SRV" not in self.alt_names:
return self.verify_jid_against_common_name(server_jid)
names = [name for name in self.alt_names.get("DNS", [])
if not name.startswith(u"*.")]
names += self.alt_names.get("XmppAddr", [])
for name in names:
logger.debug("checking {0!r} against {1!r}".format(server_jid,
name))
try:
jid = JID(name)
except ValueError:
logger.debug("Not a valid JID: {0!r}".format(name))
continue
if jid == server_jid:
logger.debug("Match!")
return True
if srv_type and self.verify_jid_against_srv_name(server_jid, srv_type):
return True
wildcards = [name[2:] for name in self.alt_names.get("DNS", [])
if name.startswith("*.")]
if not wildcards or not "." in server_jid.domain:
return False
logger.debug("checking {0!r} against wildcard domains: {1!r}"
.format(server_jid, wildcards))
server_domain = JID(domain = server_jid.domain.split(".", 1)[1])
for domain in wildcards:
logger.debug("checking {0!r} against {1!r}".format(server_domain,
domain))
try:
jid = JID(domain)
except ValueError:
logger.debug("Not a valid JID: {0!r}".format(name))
continue
if jid == server_domain:
logger.debug("Match!")
return True
return False | python | {
"resource": ""
} |
q259625 | CertificateData.verify_jid_against_common_name | validation | def verify_jid_against_common_name(self, jid):
"""Return `True` if jid is listed in the certificate commonName.
:Parameters:
- `jid`: JID requested (domain part only)
:Types:
- `jid`: `JID`
:Returntype: `bool`
"""
if not self.common_names:
return False
for name in self.common_names:
try:
cn_jid = JID(name)
except ValueError:
continue
if jid == cn_jid:
return True
return False | python | {
"resource": ""
} |
q259626 | CertificateData.verify_jid_against_srv_name | validation | def verify_jid_against_srv_name(self, jid, srv_type):
"""Check if the cerificate is valid for given domain-only JID
and a service type.
:Parameters:
- `jid`: JID requested (domain part only)
- `srv_type`: service type, e.g. 'xmpp-client'
:Types:
- `jid`: `JID`
- `srv_type`: `unicode`
:Returntype: `bool`
"""
srv_prefix = u"_" + srv_type + u"."
srv_prefix_l = len(srv_prefix)
for srv in self.alt_names.get("SRVName", []):
logger.debug("checking {0!r} against {1!r}".format(jid,
srv))
if not srv.startswith(srv_prefix):
logger.debug("{0!r} does not start with {1!r}"
.format(srv, srv_prefix))
continue
try:
srv_jid = JID(srv[srv_prefix_l:])
except ValueError:
continue
if srv_jid == jid:
logger.debug("Match!")
return True
return False | python | {
"resource": ""
} |
q259627 | CertificateData.verify_client | validation | def verify_client(self, client_jid = None, domains = None):
"""Verify certificate for a client.
Please note that `client_jid` is only a hint to choose from the names,
other JID may be returned if `client_jid` is not included in the
certificate.
:Parameters:
- `client_jid`: client name requested. May be `None` to allow
any name in one of the `domains`.
- `domains`: list of domains we can handle.
:Types:
- `client_jid`: `JID`
- `domains`: `list` of `unicode`
:Return: one of the jids in the certificate or `None` is no authorized
name is found.
"""
jids = [jid for jid in self.get_jids() if jid.local]
if not jids:
return None
if client_jid is not None and client_jid in jids:
return client_jid
if domains is None:
return jids[0]
for jid in jids:
for domain in domains:
if are_domains_equal(jid.domain, domain):
return jid
return None | python | {
"resource": ""
} |
q259628 | BasicCertificateData.from_ssl_socket | validation | def from_ssl_socket(cls, ssl_socket):
"""Load certificate data from an SSL socket.
"""
cert = cls()
try:
data = ssl_socket.getpeercert()
except AttributeError:
# PyPy doesn't have .getppercert
return cert
logger.debug("Certificate data from ssl module: {0!r}".format(data))
if not data:
return cert
cert.validated = True
cert.subject_name = data.get('subject')
cert.alt_names = defaultdict(list)
if 'subjectAltName' in data:
for name, value in data['subjectAltName']:
cert.alt_names[name].append(value)
if 'notAfter' in data:
tstamp = ssl.cert_time_to_seconds(data['notAfter'])
cert.not_after = datetime.utcfromtimestamp(tstamp)
if sys.version_info.major < 3:
cert._decode_names() # pylint: disable=W0212
cert.common_names = []
if cert.subject_name:
for part in cert.subject_name:
for name, value in part:
if name == 'commonName':
cert.common_names.append(value)
return cert | python | {
"resource": ""
} |
q259629 | ASN1CertificateData.from_ssl_socket | validation | def from_ssl_socket(cls, ssl_socket):
"""Get certificate data from an SSL socket.
"""
try:
data = ssl_socket.getpeercert(True)
except AttributeError:
# PyPy doesn't have .getpeercert
data = None
if not data:
logger.debug("No certificate infromation")
return cls()
result = cls.from_der_data(data)
result.validated = bool(ssl_socket.getpeercert())
return result | python | {
"resource": ""
} |
q259630 | ASN1CertificateData.from_der_data | validation | def from_der_data(cls, data):
"""Decode DER-encoded certificate.
:Parameters:
- `data`: the encoded certificate
:Types:
- `data`: `bytes`
:Return: decoded certificate data
:Returntype: ASN1CertificateData
"""
# pylint: disable=W0212
logger.debug("Decoding DER certificate: {0!r}".format(data))
if cls._cert_asn1_type is None:
cls._cert_asn1_type = Certificate()
cert = der_decoder.decode(data, asn1Spec = cls._cert_asn1_type)[0]
result = cls()
tbs_cert = cert.getComponentByName('tbsCertificate')
subject = tbs_cert.getComponentByName('subject')
logger.debug("Subject: {0!r}".format(subject))
result._decode_subject(subject)
validity = tbs_cert.getComponentByName('validity')
result._decode_validity(validity)
extensions = tbs_cert.getComponentByName('extensions')
if extensions:
for extension in extensions:
logger.debug("Extension: {0!r}".format(extension))
oid = extension.getComponentByName('extnID')
logger.debug("OID: {0!r}".format(oid))
if oid != SUBJECT_ALT_NAME_OID:
continue
value = extension.getComponentByName('extnValue')
logger.debug("Value: {0!r}".format(value))
if isinstance(value, Any):
# should be OctetString, but is Any
# in pyasn1_modules-0.0.1a
value = der_decoder.decode(value,
asn1Spec = OctetString())[0]
alt_names = der_decoder.decode(value,
asn1Spec = GeneralNames())[0]
logger.debug("SubjectAltName: {0!r}".format(alt_names))
result._decode_alt_names(alt_names)
return result | python | {
"resource": ""
} |
q259631 | ASN1CertificateData._decode_subject | validation | def _decode_subject(self, subject):
"""Load data from a ASN.1 subject.
"""
self.common_names = []
subject_name = []
for rdnss in subject:
for rdns in rdnss:
rdnss_list = []
for nameval in rdns:
val_type = nameval.getComponentByName('type')
value = nameval.getComponentByName('value')
if val_type not in DN_OIDS:
logger.debug("OID {0} not supported".format(val_type))
continue
val_type = DN_OIDS[val_type]
value = der_decoder.decode(value,
asn1Spec = DirectoryString())[0]
value = value.getComponent()
try:
value = _decode_asn1_string(value)
except UnicodeError:
logger.debug("Cannot decode value: {0!r}".format(value))
continue
if val_type == u"commonName":
self.common_names.append(value)
rdnss_list.append((val_type, value))
subject_name.append(tuple(rdnss_list))
self.subject_name = tuple(subject_name) | python | {
"resource": ""
} |
q259632 | ASN1CertificateData._decode_validity | validation | def _decode_validity(self, validity):
"""Load data from a ASN.1 validity value.
"""
not_after = validity.getComponentByName('notAfter')
not_after = str(not_after.getComponent())
if isinstance(not_after, GeneralizedTime):
self.not_after = datetime.strptime(not_after, "%Y%m%d%H%M%SZ")
else:
self.not_after = datetime.strptime(not_after, "%y%m%d%H%M%SZ")
self.alt_names = defaultdict(list) | python | {
"resource": ""
} |
q259633 | ASN1CertificateData._decode_alt_names | validation | def _decode_alt_names(self, alt_names):
"""Load SubjectAltName from a ASN.1 GeneralNames value.
:Values:
- `alt_names`: the SubjectAltNama extension value
:Types:
- `alt_name`: `GeneralNames`
"""
for alt_name in alt_names:
tname = alt_name.getName()
comp = alt_name.getComponent()
if tname == "dNSName":
key = "DNS"
value = _decode_asn1_string(comp)
elif tname == "uniformResourceIdentifier":
key = "URI"
value = _decode_asn1_string(comp)
elif tname == "otherName":
oid = comp.getComponentByName("type-id")
value = comp.getComponentByName("value")
if oid == XMPPADDR_OID:
key = "XmppAddr"
value = der_decoder.decode(value,
asn1Spec = UTF8String())[0]
value = _decode_asn1_string(value)
elif oid == SRVNAME_OID:
key = "SRVName"
value = der_decoder.decode(value,
asn1Spec = IA5String())[0]
value = _decode_asn1_string(value)
else:
logger.debug("Unknown other name: {0}".format(oid))
continue
else:
logger.debug("Unsupported general name: {0}"
.format(tname))
continue
self.alt_names[key].append(value) | python | {
"resource": ""
} |
q259634 | ASN1CertificateData.from_file | validation | def from_file(cls, filename):
"""Load certificate from a file.
"""
with open(filename, "r") as pem_file:
data = pem.readPemFromFile(pem_file)
return cls.from_der_data(data) | python | {
"resource": ""
} |
q259635 | RosterTool.run | validation | def run(self):
"""Request client connection and start the main loop."""
if self.args.roster_cache and os.path.exists(self.args.roster_cache):
logging.info(u"Loading roster from {0!r}"
.format(self.args.roster_cache))
try:
self.client.roster_client.load_roster(self.args.roster_cache)
except (IOError, ValueError), err:
logging.error(u"Could not load the roster: {0!r}".format(err))
self.client.connect()
self.client.run() | python | {
"resource": ""
} |
q259636 | EventDispatcher.add_handler | validation | def add_handler(self, handler):
"""Add a handler object.
:Parameters:
- `handler`: the object providing event handler methods
:Types:
- `handler`: `EventHandler`
"""
if not isinstance(handler, EventHandler):
raise TypeError, "Not an EventHandler"
with self.lock:
if handler in self.handlers:
return
self.handlers.append(handler)
self._update_handlers() | python | {
"resource": ""
} |
q259637 | EventDispatcher.remove_handler | validation | def remove_handler(self, handler):
"""Remove a handler object.
:Parameters:
- `handler`: the object to remove
"""
with self.lock:
if handler in self.handlers:
self.handlers.remove(handler)
self._update_handlers() | python | {
"resource": ""
} |
q259638 | EventDispatcher._update_handlers | validation | def _update_handlers(self):
"""Update `_handler_map` after `handlers` have been
modified."""
handler_map = defaultdict(list)
for i, obj in enumerate(self.handlers):
for dummy, handler in inspect.getmembers(obj, callable):
if not hasattr(handler, "_pyxmpp_event_handled"):
continue
# pylint: disable-msg=W0212
event_class = handler._pyxmpp_event_handled
handler_map[event_class].append( (i, handler) )
self._handler_map = handler_map | python | {
"resource": ""
} |
q259639 | EventDispatcher.dispatch | validation | def dispatch(self, block = False, timeout = None):
"""Get the next event from the queue and pass it to
the appropriate handlers.
:Parameters:
- `block`: wait for event if the queue is empty
- `timeout`: maximum time, in seconds, to wait if `block` is `True`
:Types:
- `block`: `bool`
- `timeout`: `float`
:Return: the event handled (may be `QUIT`) or `None`
"""
logger.debug(" dispatching...")
try:
event = self.queue.get(block, timeout)
except Queue.Empty:
logger.debug(" queue empty")
return None
try:
logger.debug(" event: {0!r}".format(event))
if event is QUIT:
return QUIT
handlers = list(self._handler_map[None])
klass = event.__class__
if klass in self._handler_map:
handlers += self._handler_map[klass]
logger.debug(" handlers: {0!r}".format(handlers))
# to restore the original order of handler objects
handlers.sort(key = lambda x: x[0])
for dummy, handler in handlers:
logger.debug(u" passing the event to: {0!r}".format(handler))
result = handler(event)
if isinstance(result, Event):
self.queue.put(result)
elif result and event is not QUIT:
return event
return event
finally:
self.queue.task_done() | python | {
"resource": ""
} |
q259640 | EventDispatcher.flush | validation | def flush(self, dispatch = True):
"""Read all events currently in the queue and dispatch them to the
handlers unless `dispatch` is `False`.
Note: If the queue contains `QUIT` the events after it won't be
removed.
:Parameters:
- `dispatch`: if the events should be handled (`True`) or ignored
(`False`)
:Return: `QUIT` if the `QUIT` event was reached.
"""
if dispatch:
while True:
event = self.dispatch(False)
if event in (None, QUIT):
return event
else:
while True:
try:
self.queue.get(False)
except Queue.Empty:
return None | python | {
"resource": ""
} |
q259641 | SCRAMClientAuthenticator.challenge | validation | def challenge(self, challenge):
"""Process a challenge and return the response.
:Parameters:
- `challenge`: the challenge from server.
:Types:
- `challenge`: `bytes`
:return: the response or a failure indicator.
:returntype: `sasl.Response` or `sasl.Failure`
"""
# pylint: disable=R0911
if not challenge:
logger.debug("Empty challenge")
return Failure("bad-challenge")
if self._server_first_message:
return self._final_challenge(challenge)
match = SERVER_FIRST_MESSAGE_RE.match(challenge)
if not match:
logger.debug("Bad challenge syntax: {0!r}".format(challenge))
return Failure("bad-challenge")
self._server_first_message = challenge
mext = match.group("mext")
if mext:
logger.debug("Unsupported extension received: {0!r}".format(mext))
return Failure("bad-challenge")
nonce = match.group("nonce")
if not nonce.startswith(self._c_nonce):
logger.debug("Nonce does not start with our nonce")
return Failure("bad-challenge")
salt = match.group("salt")
try:
salt = a2b_base64(salt)
except ValueError:
logger.debug("Bad base64 encoding for salt: {0!r}".format(salt))
return Failure("bad-challenge")
iteration_count = match.group("iteration_count")
try:
iteration_count = int(iteration_count)
except ValueError:
logger.debug("Bad iteration_count: {0!r}".format(iteration_count))
return Failure("bad-challenge")
return self._make_response(nonce, salt, iteration_count) | python | {
"resource": ""
} |
q259642 | SCRAMClientAuthenticator._make_response | validation | def _make_response(self, nonce, salt, iteration_count):
"""Make a response for the first challenge from the server.
:return: the response or a failure indicator.
:returntype: `sasl.Response` or `sasl.Failure`
"""
self._salted_password = self.Hi(self.Normalize(self.password), salt,
iteration_count)
self.password = None # not needed any more
if self.channel_binding:
channel_binding = b"c=" + standard_b64encode(self._gs2_header +
self._cb_data)
else:
channel_binding = b"c=" + standard_b64encode(self._gs2_header)
# pylint: disable=C0103
client_final_message_without_proof = (channel_binding + b",r=" + nonce)
client_key = self.HMAC(self._salted_password, b"Client Key")
stored_key = self.H(client_key)
auth_message = ( self._client_first_message_bare + b"," +
self._server_first_message + b"," +
client_final_message_without_proof )
self._auth_message = auth_message
client_signature = self.HMAC(stored_key, auth_message)
client_proof = self.XOR(client_key, client_signature)
proof = b"p=" + standard_b64encode(client_proof)
client_final_message = (client_final_message_without_proof + b"," +
proof)
return Response(client_final_message) | python | {
"resource": ""
} |
q259643 | SCRAMClientAuthenticator._final_challenge | validation | def _final_challenge(self, challenge):
"""Process the second challenge from the server and return the
response.
:Parameters:
- `challenge`: the challenge from server.
:Types:
- `challenge`: `bytes`
:return: the response or a failure indicator.
:returntype: `sasl.Response` or `sasl.Failure`
"""
if self._finished:
return Failure("extra-challenge")
match = SERVER_FINAL_MESSAGE_RE.match(challenge)
if not match:
logger.debug("Bad final message syntax: {0!r}".format(challenge))
return Failure("bad-challenge")
error = match.group("error")
if error:
logger.debug("Server returned SCRAM error: {0!r}".format(error))
return Failure(u"scram-" + error.decode("utf-8"))
verifier = match.group("verifier")
if not verifier:
logger.debug("No verifier value in the final message")
return Failure("bad-succes")
server_key = self.HMAC(self._salted_password, b"Server Key")
server_signature = self.HMAC(server_key, self._auth_message)
if server_signature != a2b_base64(verifier):
logger.debug("Server verifier does not match")
return Failure("bad-succes")
self._finished = True
return Response(None) | python | {
"resource": ""
} |
q259644 | SCRAMClientAuthenticator.finish | validation | def finish(self, data):
"""Process success indicator from the server.
Process any addiitional data passed with the success.
Fail if the server was not authenticated.
:Parameters:
- `data`: an optional additional data with success.
:Types:
- `data`: `bytes`
:return: success or failure indicator.
:returntype: `sasl.Success` or `sasl.Failure`"""
if not self._server_first_message:
logger.debug("Got success too early")
return Failure("bad-success")
if self._finished:
return Success({"username": self.username, "authzid": self.authzid})
else:
ret = self._final_challenge(data)
if isinstance(ret, Failure):
return ret
if self._finished:
return Success({"username": self.username,
"authzid": self.authzid})
else:
logger.debug("Something went wrong when processing additional"
" data with success?")
return Failure("bad-success") | python | {
"resource": ""
} |
q259645 | feature_uri | validation | def feature_uri(uri):
"""Decorating attaching a feature URI (for Service Discovery or Capability
to a XMPPFeatureHandler class."""
def decorator(class_):
"""Returns a decorated class"""
if "_pyxmpp_feature_uris" not in class_.__dict__:
class_._pyxmpp_feature_uris = set()
class_._pyxmpp_feature_uris.add(uri)
return class_
return decorator | python | {
"resource": ""
} |
q259646 | payload_element_name | validation | def payload_element_name(element_name):
"""Class decorator generator for decorationg
`StanzaPayload` subclasses.
:Parameters:
- `element_name`: XML element qname handled by the class
:Types:
- `element_name`: `unicode`
"""
def decorator(klass):
"""The payload_element_name decorator."""
# pylint: disable-msg=W0212,W0404
from .stanzapayload import STANZA_PAYLOAD_CLASSES
from .stanzapayload import STANZA_PAYLOAD_ELEMENTS
if hasattr(klass, "_pyxmpp_payload_element_name"):
klass._pyxmpp_payload_element_name.append(element_name)
else:
klass._pyxmpp_payload_element_name = [element_name]
if element_name in STANZA_PAYLOAD_CLASSES:
logger = logging.getLogger('pyxmpp.payload_element_name')
logger.warning("Overriding payload class for {0!r}".format(
element_name))
STANZA_PAYLOAD_CLASSES[element_name] = klass
STANZA_PAYLOAD_ELEMENTS[klass].append(element_name)
return klass
return decorator | python | {
"resource": ""
} |
q259647 | stream_element_handler | validation | def stream_element_handler(element_name, usage_restriction = None):
"""Method decorator generator for decorating stream element
handler methods in `StreamFeatureHandler` subclasses.
:Parameters:
- `element_name`: stream element QName
- `usage_restriction`: optional usage restriction: "initiator" or
"receiver"
:Types:
- `element_name`: `unicode`
- `usage_restriction`: `unicode`
"""
def decorator(func):
"""The decorator"""
func._pyxmpp_stream_element_handled = element_name
func._pyxmpp_usage_restriction = usage_restriction
return func
return decorator | python | {
"resource": ""
} |
q259648 | Option._new_from_xml | validation | def _new_from_xml(cls, xmlnode):
"""Create a new `Option` object from an XML element.
:Parameters:
- `xmlnode`: the XML element.
:Types:
- `xmlnode`: `libxml2.xmlNode`
:return: the object created.
:returntype: `Option`
"""
label = from_utf8(xmlnode.prop("label"))
child = xmlnode.children
value = None
for child in xml_element_ns_iter(xmlnode.children, DATAFORM_NS):
if child.name == "value":
value = from_utf8(child.getContent())
break
if value is None:
raise BadRequestProtocolError("No value in <option/> element")
return cls(value, label) | python | {
"resource": ""
} |
q259649 | Field.add_option | validation | def add_option(self, value, label):
"""Add an option for the field.
:Parameters:
- `value`: option values.
- `label`: option label (human-readable description).
:Types:
- `value`: `list` of `unicode`
- `label`: `unicode`
"""
if type(value) is list:
warnings.warn(".add_option() accepts single value now.", DeprecationWarning, stacklevel=1)
value = value[0]
if self.type not in ("list-multi", "list-single"):
raise ValueError("Options are allowed only for list types.")
option = Option(value, label)
self.options.append(option)
return option | python | {
"resource": ""
} |
q259650 | Field._new_from_xml | validation | def _new_from_xml(cls, xmlnode):
"""Create a new `Field` object from an XML element.
:Parameters:
- `xmlnode`: the XML element.
:Types:
- `xmlnode`: `libxml2.xmlNode`
:return: the object created.
:returntype: `Field`
"""
field_type = xmlnode.prop("type")
label = from_utf8(xmlnode.prop("label"))
name = from_utf8(xmlnode.prop("var"))
child = xmlnode.children
values = []
options = []
required = False
desc = None
while child:
if child.type != "element" or child.ns().content != DATAFORM_NS:
pass
elif child.name == "required":
required = True
elif child.name == "desc":
desc = from_utf8(child.getContent())
elif child.name == "value":
values.append(from_utf8(child.getContent()))
elif child.name == "option":
options.append(Option._new_from_xml(child))
child = child.next
if field_type and not field_type.endswith("-multi") and len(values) > 1:
raise BadRequestProtocolError("Multiple values for a single-value field")
return cls(name, values, field_type, label, options, required, desc) | python | {
"resource": ""
} |
q259651 | Item.add_field | validation | def add_field(self, name = None, values = None, field_type = None,
label = None, options = None, required = False, desc = None, value = None):
"""Add a field to the item.
:Parameters:
- `name`: field name.
- `values`: raw field values. Not to be used together with `value`.
- `field_type`: field type.
- `label`: field label.
- `options`: optional values for the field.
- `required`: `True` if the field is required.
- `desc`: natural-language description of the field.
- `value`: field value or values in a field_type-specific type. May be used only
if `values` parameter is not provided.
:Types:
- `name`: `unicode`
- `values`: `list` of `unicode`
- `field_type`: `str`
- `label`: `unicode`
- `options`: `list` of `Option`
- `required`: `bool`
- `desc`: `unicode`
- `value`: `bool` for "boolean" field, `JID` for "jid-single", `list` of `JID`
for "jid-multi", `list` of `unicode` for "list-multi" and "text-multi"
and `unicode` for other field types.
:return: the field added.
:returntype: `Field`
"""
field = Field(name, values, field_type, label, options, required, desc, value)
self.fields.append(field)
return field | python | {
"resource": ""
} |
q259652 | Item._new_from_xml | validation | def _new_from_xml(cls, xmlnode):
"""Create a new `Item` object from an XML element.
:Parameters:
- `xmlnode`: the XML element.
:Types:
- `xmlnode`: `libxml2.xmlNode`
:return: the object created.
:returntype: `Item`
"""
child = xmlnode.children
fields = []
while child:
if child.type != "element" or child.ns().content != DATAFORM_NS:
pass
elif child.name == "field":
fields.append(Field._new_from_xml(child))
child = child.next
return cls(fields) | python | {
"resource": ""
} |
q259653 | Form.add_item | validation | def add_item(self, fields = None):
"""Add and item to the form.
:Parameters:
- `fields`: fields of the item (they may be added later).
:Types:
- `fields`: `list` of `Field`
:return: the item added.
:returntype: `Item`
"""
item = Item(fields)
self.items.append(item)
return item | python | {
"resource": ""
} |
q259654 | Form.make_submit | validation | def make_submit(self, keep_types = False):
"""Make a "submit" form using data in `self`.
Remove uneeded information from the form. The information removed
includes: title, instructions, field labels, fixed fields etc.
:raise ValueError: when any required field has no value.
:Parameters:
- `keep_types`: when `True` field type information will be included
in the result form. That is usually not needed.
:Types:
- `keep_types`: `bool`
:return: the form created.
:returntype: `Form`"""
result = Form("submit")
for field in self.fields:
if field.type == "fixed":
continue
if not field.values:
if field.required:
raise ValueError("Required field with no value!")
continue
if keep_types:
result.add_field(field.name, field.values, field.type)
else:
result.add_field(field.name, field.values)
return result | python | {
"resource": ""
} |
q259655 | Form.__from_xml | validation | def __from_xml(self, xmlnode):
"""Initialize a `Form` object from an XML element.
:Parameters:
- `xmlnode`: the XML element.
:Types:
- `xmlnode`: `libxml2.xmlNode`
"""
self.fields = []
self.reported_fields = []
self.items = []
self.title = None
self.instructions = None
if (xmlnode.type != "element" or xmlnode.name != "x"
or xmlnode.ns().content != DATAFORM_NS):
raise ValueError("Not a form: " + xmlnode.serialize())
self.type = xmlnode.prop("type")
if not self.type in self.allowed_types:
raise BadRequestProtocolError("Bad form type: %r" % (self.type,))
child = xmlnode.children
while child:
if child.type != "element" or child.ns().content != DATAFORM_NS:
pass
elif child.name == "title":
self.title = from_utf8(child.getContent())
elif child.name == "instructions":
self.instructions = from_utf8(child.getContent())
elif child.name == "field":
self.fields.append(Field._new_from_xml(child))
elif child.name == "item":
self.items.append(Item._new_from_xml(child))
elif child.name == "reported":
self.__get_reported(child)
child = child.next | python | {
"resource": ""
} |
q259656 | register_disco_cache_fetchers | validation | def register_disco_cache_fetchers(cache_suite,stream):
"""Register Service Discovery cache fetchers into given
cache suite and using the stream provided.
:Parameters:
- `cache_suite`: the cache suite where the fetchers are to be
registered.
- `stream`: the stream to be used by the fetchers.
:Types:
- `cache_suite`: `cache.CacheSuite`
- `stream`: `pyxmpp.stream.Stream`
"""
tmp=stream
class DiscoInfoCacheFetcher(DiscoCacheFetcherBase):
"""Cache fetcher for DiscoInfo."""
stream=tmp
disco_class=DiscoInfo
class DiscoItemsCacheFetcher(DiscoCacheFetcherBase):
"""Cache fetcher for DiscoItems."""
stream=tmp
disco_class=DiscoItems
cache_suite.register_fetcher(DiscoInfo,DiscoInfoCacheFetcher)
cache_suite.register_fetcher(DiscoItems,DiscoItemsCacheFetcher) | python | {
"resource": ""
} |
q259657 | DiscoItem.remove | validation | def remove(self):
"""Remove `self` from the containing `DiscoItems` object."""
if self.disco is None:
return
self.xmlnode.unlinkNode()
oldns=self.xmlnode.ns()
ns=self.xmlnode.newNs(oldns.getContent(),None)
self.xmlnode.replaceNs(oldns,ns)
common_root.addChild(self.xmlnode())
self.disco=None | python | {
"resource": ""
} |
q259658 | DiscoItem.set_node | validation | def set_node(self,node):
"""Set the node of the item.
:Parameters:
- `node`: the new node or `None`.
:Types:
- `node`: `unicode`
"""
if node is None:
if self.xmlnode.hasProp("node"):
self.xmlnode.unsetProp("node")
return
node = unicode(node)
self.xmlnode.setProp("node", node.encode("utf-8")) | python | {
"resource": ""
} |
q259659 | DiscoItem.set_action | validation | def set_action(self,action):
"""Set the action of the item.
:Parameters:
- `action`: the new action or `None`.
:Types:
- `action`: `unicode`
"""
if action is None:
if self.xmlnode.hasProp("action"):
self.xmlnode.unsetProp("action")
return
if action not in ("remove","update"):
raise ValueError("Action must be 'update' or 'remove'")
action = unicode(action)
self.xmlnode.setProp("action", action.encode("utf-8")) | python | {
"resource": ""
} |
q259660 | DiscoIdentity.get_name | validation | def get_name(self):
"""Get the name of the item.
:return: the name of the item or `None`.
:returntype: `unicode`"""
var = self.xmlnode.prop("name")
if not var:
var = ""
return var.decode("utf-8") | python | {
"resource": ""
} |
q259661 | DiscoIdentity.get_category | validation | def get_category(self):
"""Get the category of the item.
:return: the category of the item.
:returntype: `unicode`"""
var = self.xmlnode.prop("category")
if not var:
var = "?"
return var.decode("utf-8") | python | {
"resource": ""
} |
q259662 | DiscoIdentity.set_category | validation | def set_category(self, category):
"""Set the category of the item.
:Parameters:
- `category`: the new category.
:Types:
- `category`: `unicode` """
if not category:
raise ValueError("Category is required in DiscoIdentity")
category = unicode(category)
self.xmlnode.setProp("category", category.encode("utf-8")) | python | {
"resource": ""
} |
q259663 | DiscoIdentity.get_type | validation | def get_type(self):
"""Get the type of the item.
:return: the type of the item.
:returntype: `unicode`"""
item_type = self.xmlnode.prop("type")
if not item_type:
item_type = "?"
return item_type.decode("utf-8") | python | {
"resource": ""
} |
q259664 | DiscoIdentity.set_type | validation | def set_type(self, item_type):
"""Set the type of the item.
:Parameters:
- `item_type`: the new type.
:Types:
- `item_type`: `unicode` """
if not item_type:
raise ValueError("Type is required in DiscoIdentity")
item_type = unicode(item_type)
self.xmlnode.setProp("type", item_type.encode("utf-8")) | python | {
"resource": ""
} |
q259665 | DiscoItems.get_items | validation | def get_items(self):
"""Get the items contained in `self`.
:return: the items contained.
:returntype: `list` of `DiscoItem`"""
ret=[]
l=self.xpath_ctxt.xpathEval("d:item")
if l is not None:
for i in l:
ret.append(DiscoItem(self, i))
return ret | python | {
"resource": ""
} |
q259666 | DiscoItems.add_item | validation | def add_item(self,jid,node=None,name=None,action=None):
"""Add a new item to the `DiscoItems` object.
:Parameters:
- `jid`: item JID.
- `node`: item node name.
- `name`: item name.
- `action`: action for a "disco push".
:Types:
- `jid`: `pyxmpp.JID`
- `node`: `unicode`
- `name`: `unicode`
- `action`: `unicode`
:returns: the item created.
:returntype: `DiscoItem`."""
return DiscoItem(self,jid,node,name,action) | python | {
"resource": ""
} |
q259667 | DiscoItems.has_item | validation | def has_item(self,jid,node=None):
"""Check if `self` contains an item.
:Parameters:
- `jid`: JID of the item.
- `node`: node name of the item.
:Types:
- `jid`: `JID`
- `node`: `libxml2.xmlNode`
:return: `True` if the item is found in `self`.
:returntype: `bool`"""
l=self.xpath_ctxt.xpathEval("d:item")
if l is None:
return False
for it in l:
di=DiscoItem(self,it)
if di.jid==jid and di.node==node:
return True
return False | python | {
"resource": ""
} |
q259668 | DiscoInfo.get_features | validation | def get_features(self):
"""Get the features contained in `self`.
:return: the list of features.
:returntype: `list` of `unicode`"""
l = self.xpath_ctxt.xpathEval("d:feature")
ret = []
for f in l:
if f.hasProp("var"):
ret.append( f.prop("var").decode("utf-8") )
return ret | python | {
"resource": ""
} |
q259669 | DiscoInfo.has_feature | validation | def has_feature(self,var):
"""Check if `self` contains the named feature.
:Parameters:
- `var`: the feature name.
:Types:
- `var`: `unicode`
:return: `True` if the feature is found in `self`.
:returntype: `bool`"""
if not var:
raise ValueError("var is None")
if '"' not in var:
expr=u'd:feature[@var="%s"]' % (var,)
elif "'" not in var:
expr=u"d:feature[@var='%s']" % (var,)
else:
raise ValueError("Invalid feature name")
l=self.xpath_ctxt.xpathEval(to_utf8(expr))
if l:
return True
else:
return False | python | {
"resource": ""
} |
q259670 | DiscoInfo.add_feature | validation | def add_feature(self,var):
"""Add a feature to `self`.
:Parameters:
- `var`: the feature name.
:Types:
- `var`: `unicode`"""
if self.has_feature(var):
return
n=self.xmlnode.newChild(None, "feature", None)
n.setProp("var", to_utf8(var)) | python | {
"resource": ""
} |
q259671 | DiscoInfo.remove_feature | validation | def remove_feature(self,var):
"""Remove a feature from `self`.
:Parameters:
- `var`: the feature name.
:Types:
- `var`: `unicode`"""
if not var:
raise ValueError("var is None")
if '"' not in var:
expr='d:feature[@var="%s"]' % (var,)
elif "'" not in var:
expr="d:feature[@var='%s']" % (var,)
else:
raise ValueError("Invalid feature name")
l=self.xpath_ctxt.xpathEval(expr)
if not l:
return
for f in l:
f.unlinkNode()
f.freeNode() | python | {
"resource": ""
} |
q259672 | DiscoInfo.get_identities | validation | def get_identities(self):
"""List the identity objects contained in `self`.
:return: the list of identities.
:returntype: `list` of `DiscoIdentity`"""
ret=[]
l=self.xpath_ctxt.xpathEval("d:identity")
if l is not None:
for i in l:
ret.append(DiscoIdentity(self,i))
return ret | python | {
"resource": ""
} |
q259673 | DiscoInfo.identity_is | validation | def identity_is(self,item_category,item_type=None):
"""Check if the item described by `self` belongs to the given category
and type.
:Parameters:
- `item_category`: the category name.
- `item_type`: the type name. If `None` then only the category is
checked.
:Types:
- `item_category`: `unicode`
- `item_type`: `unicode`
:return: `True` if `self` contains at least one <identity/> object with
given type and category.
:returntype: `bool`"""
if not item_category:
raise ValueError("bad category")
if not item_type:
type_expr=u""
elif '"' not in item_type:
type_expr=u' and @type="%s"' % (item_type,)
elif "'" not in type:
type_expr=u" and @type='%s'" % (item_type,)
else:
raise ValueError("Invalid type name")
if '"' not in item_category:
expr=u'd:identity[@category="%s"%s]' % (item_category,type_expr)
elif "'" not in item_category:
expr=u"d:identity[@category='%s'%s]" % (item_category,type_expr)
else:
raise ValueError("Invalid category name")
l=self.xpath_ctxt.xpathEval(to_utf8(expr))
if l:
return True
else:
return False | python | {
"resource": ""
} |
q259674 | DiscoInfo.add_identity | validation | def add_identity(self,item_name,item_category=None,item_type=None):
"""Add an identity to the `DiscoInfo` object.
:Parameters:
- `item_name`: name of the item.
- `item_category`: category of the item.
- `item_type`: type of the item.
:Types:
- `item_name`: `unicode`
- `item_category`: `unicode`
- `item_type`: `unicode`
:returns: the identity created.
:returntype: `DiscoIdentity`"""
return DiscoIdentity(self,item_name,item_category,item_type) | python | {
"resource": ""
} |
q259675 | DiscoCacheFetcherBase.fetch | validation | def fetch(self):
"""Initialize the Service Discovery process."""
from ..iq import Iq
jid,node = self.address
iq = Iq(to_jid = jid, stanza_type = "get")
disco = self.disco_class(node)
iq.add_content(disco.xmlnode)
self.stream.set_response_handlers(iq,self.__response, self.__error,
self.__timeout)
self.stream.send(iq) | python | {
"resource": ""
} |
q259676 | DiscoCacheFetcherBase.__response | validation | def __response(self,stanza):
"""Handle successful disco response.
:Parameters:
- `stanza`: the stanza received.
:Types:
- `stanza`: `pyxmpp.stanza.Stanza`"""
try:
d=self.disco_class(stanza.get_query())
self.got_it(d)
except ValueError,e:
self.error(e) | python | {
"resource": ""
} |
q259677 | DiscoCacheFetcherBase.__error | validation | def __error(self,stanza):
"""Handle disco error response.
:Parameters:
- `stanza`: the stanza received.
:Types:
- `stanza`: `pyxmpp.stanza.Stanza`"""
try:
self.error(stanza.get_error())
except ProtocolError:
from ..error import StanzaErrorNode
self.error(StanzaErrorNode("undefined-condition")) | python | {
"resource": ""
} |
q259678 | Iq.make_error_response | validation | def make_error_response(self, cond):
"""Create error response for the a "get" or "set" iq stanza.
:Parameters:
- `cond`: error condition name, as defined in XMPP specification.
:return: new `Iq` object with the same "id" as self, "from" and "to"
attributes swapped, type="error" and containing <error /> element
plus payload of `self`.
:returntype: `Iq`"""
if self.stanza_type in ("result", "error"):
raise ValueError("Errors may not be generated for"
" 'result' and 'error' iq")
stanza = Iq(stanza_type="error", from_jid = self.to_jid,
to_jid = self.from_jid, stanza_id = self.stanza_id,
error_cond = cond)
if self._payload is None:
self.decode_payload()
for payload in self._payload:
# use Stanza.add_payload to skip the payload length check
Stanza.add_payload(stanza, payload)
return stanza | python | {
"resource": ""
} |
q259679 | Iq.make_result_response | validation | def make_result_response(self):
"""Create result response for the a "get" or "set" iq stanza.
:return: new `Iq` object with the same "id" as self, "from" and "to"
attributes replaced and type="result".
:returntype: `Iq`"""
if self.stanza_type not in ("set", "get"):
raise ValueError("Results may only be generated for"
" 'set' or 'get' iq")
stanza = Iq(stanza_type = "result", from_jid = self.to_jid,
to_jid = self.from_jid, stanza_id = self.stanza_id)
return stanza | python | {
"resource": ""
} |
q259680 | StreamTLSHandler._request_tls | validation | def _request_tls(self):
"""Request a TLS-encrypted connection.
[initiating entity only]"""
self.requested = True
element = ElementTree.Element(STARTTLS_TAG)
self.stream.write_element(element) | python | {
"resource": ""
} |
q259681 | StreamTLSHandler._make_tls_connection | validation | def _make_tls_connection(self):
"""Initiate TLS connection.
[initiating entity only]
"""
logger.debug("Preparing TLS connection")
if self.settings["tls_verify_peer"]:
cert_reqs = ssl.CERT_REQUIRED
else:
cert_reqs = ssl.CERT_NONE
self.stream.transport.starttls(
keyfile = self.settings["tls_key_file"],
certfile = self.settings["tls_cert_file"],
server_side = not self.stream.initiator,
cert_reqs = cert_reqs,
ssl_version = ssl.PROTOCOL_TLSv1,
ca_certs = self.settings["tls_cacert_file"],
do_handshake_on_connect = False,
) | python | {
"resource": ""
} |
q259682 | StreamTLSHandler.handle_tls_connected_event | validation | def handle_tls_connected_event(self, event):
"""Verify the peer certificate on the `TLSConnectedEvent`.
"""
if self.settings["tls_verify_peer"]:
valid = self.settings["tls_verify_callback"](event.stream,
event.peer_certificate)
if not valid:
raise SSLError("Certificate verification failed")
event.stream.tls_established = True
with event.stream.lock:
event.stream._restart_stream() | python | {
"resource": ""
} |
q259683 | StreamTLSHandler.is_certificate_valid | validation | def is_certificate_valid(stream, cert):
"""Default certificate verification callback for TLS connections.
:Parameters:
- `cert`: certificate information
:Types:
- `cert`: `CertificateData`
:return: computed verification result.
"""
try:
logger.debug("tls_is_certificate_valid(cert = {0!r})".format(cert))
if not cert:
logger.warning("No TLS certificate information received.")
return False
if not cert.validated:
logger.warning("TLS certificate not validated.")
return False
srv_type = stream.transport._dst_service # pylint: disable=W0212
if cert.verify_server(stream.peer, srv_type):
logger.debug(" tls: certificate valid for {0!r}"
.format(stream.peer))
return True
else:
logger.debug(" tls: certificate not valid for {0!r}"
.format(stream.peer))
return False
except:
logger.exception("Exception caught while checking a certificate")
raise | python | {
"resource": ""
} |
q259684 | main | validation | def main():
"""Parse the command-line arguments and run the tool."""
parser = argparse.ArgumentParser(description = 'XMPP version checker',
parents = [XMPPSettings.get_arg_parser()])
parser.add_argument('source', metavar = 'SOURCE',
help = 'Source JID')
parser.add_argument('target', metavar = 'TARGET', nargs = '?',
help = 'Target JID (default: domain of SOURCE)')
parser.add_argument('--debug',
action = 'store_const', dest = 'log_level',
const = logging.DEBUG, default = logging.INFO,
help = 'Print debug messages')
parser.add_argument('--quiet', const = logging.ERROR,
action = 'store_const', dest = 'log_level',
help = 'Print only error messages')
args = parser.parse_args()
settings = XMPPSettings()
settings.load_arguments(args)
if settings.get("password") is None:
password = getpass("{0!r} password: ".format(args.source))
if sys.version_info.major < 3:
password = password.decode("utf-8")
settings["password"] = password
if sys.version_info.major < 3:
args.source = args.source.decode("utf-8")
source = JID(args.source)
if args.target:
if sys.version_info.major < 3:
args.target = args.target.decode("utf-8")
target = JID(args.target)
else:
target = JID(source.domain)
logging.basicConfig(level = args.log_level)
checker = VersionChecker(source, target, settings)
try:
checker.run()
except KeyboardInterrupt:
checker.disconnect() | python | {
"resource": ""
} |
q259685 | VersionChecker.handle_authorized | validation | def handle_authorized(self, event):
"""Send the initial presence after log-in."""
request_software_version(self.client, self.target_jid,
self.success, self.failure) | python | {
"resource": ""
} |
q259686 | ExpiringDictionary.set_item | validation | def set_item(self, key, value, timeout = None, timeout_callback = None):
"""Set item of the dictionary.
:Parameters:
- `key`: the key.
- `value`: the object to store.
- `timeout`: timeout value for the object (in seconds from now).
- `timeout_callback`: function to be called when the item expires.
The callback should accept none, one (the key) or two (the key
and the value) arguments.
:Types:
- `key`: any hashable value
- `value`: any python object
- `timeout`: `int`
- `timeout_callback`: callable
"""
with self._lock:
logger.debug("expdict.__setitem__({0!r}, {1!r}, {2!r}, {3!r})"
.format(key, value, timeout, timeout_callback))
if not timeout:
timeout = self._default_timeout
self._timeouts[key] = (time.time() + timeout, timeout_callback)
return dict.__setitem__(self, key, value) | python | {
"resource": ""
} |
q259687 | ExpiringDictionary.expire | validation | def expire(self):
"""Do the expiration of dictionary items.
Remove items that expired by now from the dictionary.
:Return: time, in seconds, when the next item expires or `None`
:returntype: `float`
"""
with self._lock:
logger.debug("expdict.expire. timeouts: {0!r}"
.format(self._timeouts))
next_timeout = None
for k in self._timeouts.keys():
ret = self._expire_item(k)
if ret is not None:
if next_timeout is None:
next_timeout = ret
else:
next_timeout = min(next_timeout, ret)
return next_timeout | python | {
"resource": ""
} |
q259688 | ExpiringDictionary._expire_item | validation | def _expire_item(self, key):
"""Do the expiration of a dictionary item.
Remove the item if it has expired by now.
:Parameters:
- `key`: key to the object.
:Types:
- `key`: any hashable value
"""
(timeout, callback) = self._timeouts[key]
now = time.time()
if timeout <= now:
item = dict.pop(self, key)
del self._timeouts[key]
if callback:
try:
callback(key, item)
except TypeError:
try:
callback(key)
except TypeError:
callback()
return None
else:
return timeout - now | python | {
"resource": ""
} |
q259689 | Stanza._decode_attributes | validation | def _decode_attributes(self):
"""Decode attributes of the stanza XML element
and put them into the stanza properties."""
try:
from_jid = self._element.get('from')
if from_jid:
self._from_jid = JID(from_jid)
to_jid = self._element.get('to')
if to_jid:
self._to_jid = JID(to_jid)
except ValueError:
raise JIDMalformedProtocolError
self._stanza_type = self._element.get('type')
self._stanza_id = self._element.get('id')
lang = self._element.get(XML_LANG_QNAME)
if lang:
self._language = lang | python | {
"resource": ""
} |
q259690 | Stanza._decode_error | validation | def _decode_error(self):
"""Decode error element of the stanza."""
error_qname = self._ns_prefix + "error"
for child in self._element:
if child.tag == error_qname:
self._error = StanzaErrorElement(child)
return
raise BadRequestProtocolError("Error element missing in"
" an error stanza") | python | {
"resource": ""
} |
q259691 | Stanza.set_payload | validation | def set_payload(self, payload):
"""Set stanza payload to a single item.
All current stanza content of will be dropped.
Marks the stanza dirty.
:Parameters:
- `payload`: XML element or stanza payload object to use
:Types:
- `payload`: :etree:`ElementTree.Element` or `StanzaPayload`
"""
if isinstance(payload, ElementClass):
self._payload = [ XMLPayload(payload) ]
elif isinstance(payload, StanzaPayload):
self._payload = [ payload ]
else:
raise TypeError("Bad payload type")
self._dirty = True | python | {
"resource": ""
} |
q259692 | Stanza.add_payload | validation | def add_payload(self, payload):
"""Add new the stanza payload.
Marks the stanza dirty.
:Parameters:
- `payload`: XML element or stanza payload object to add
:Types:
- `payload`: :etree:`ElementTree.Element` or `StanzaPayload`
"""
if self._payload is None:
self.decode_payload()
if isinstance(payload, ElementClass):
self._payload.append(XMLPayload(payload))
elif isinstance(payload, StanzaPayload):
self._payload.append(payload)
else:
raise TypeError("Bad payload type")
self._dirty = True | python | {
"resource": ""
} |
q259693 | Stanza.get_all_payload | validation | def get_all_payload(self, specialize = False):
"""Return list of stanza payload objects.
:Parameters:
- `specialize`: If `True`, then return objects of specialized
`StanzaPayload` classes whenever possible, otherwise the
representation already available will be used (often
`XMLPayload`)
:Returntype: `list` of `StanzaPayload`
"""
if self._payload is None:
self.decode_payload(specialize)
elif specialize:
for i, payload in enumerate(self._payload):
if isinstance(payload, XMLPayload):
klass = payload_class_for_element_name(
payload.element.tag)
if klass is not XMLPayload:
payload = klass.from_xml(payload.element)
self._payload[i] = payload
return list(self._payload) | python | {
"resource": ""
} |
q259694 | Stanza.get_payload | validation | def get_payload(self, payload_class, payload_key = None,
specialize = False):
"""Get the first payload item matching the given class
and optional key.
Payloads may be addressed using a specific payload class or
via the generic `XMLPayload` element, though the `XMLPayload`
representation is available only as long as the element is not
requested by a more specific type.
:Parameters:
- `payload_class`: requested payload class, a subclass of
`StanzaPayload`. If `None` get the first payload in whatever
class is available.
- `payload_key`: optional key for additional match. When used
with `payload_class` = `XMLPayload` this selects the element to
match
- `specialize`: If `True`, and `payload_class` is `None` then
return object of a specialized `StanzaPayload` subclass whenever
possible
:Types:
- `payload_class`: `StanzaPayload`
- `specialize`: `bool`
:Return: payload element found or `None`
:Returntype: `StanzaPayload`
"""
if self._payload is None:
self.decode_payload()
if payload_class is None:
if self._payload:
payload = self._payload[0]
if specialize and isinstance(payload, XMLPayload):
klass = payload_class_for_element_name(
payload.element.tag)
if klass is not XMLPayload:
payload = klass.from_xml(payload.element)
self._payload[0] = payload
return payload
else:
return None
# pylint: disable=W0212
elements = payload_class._pyxmpp_payload_element_name
for i, payload in enumerate(self._payload):
if isinstance(payload, XMLPayload):
if payload_class is not XMLPayload:
if payload.xml_element_name not in elements:
continue
payload = payload_class.from_xml(payload.element)
elif not isinstance(payload, payload_class):
continue
if payload_key is not None and payload_key != payload.handler_key():
continue
self._payload[i] = payload
return payload
return None | python | {
"resource": ""
} |
q259695 | element_to_unicode | validation | def element_to_unicode(element):
"""Serialize an XML element into a unicode string.
This should work the same on Python2 and Python3 and with all
:etree:`ElementTree` implementations.
:Parameters:
- `element`: the XML element to serialize
:Types:
- `element`: :etree:`ElementTree.Element`
"""
if hasattr(ElementTree, 'tounicode'):
# pylint: disable=E1103
return ElementTree.tounicode("element")
elif sys.version_info.major < 3:
return unicode(ElementTree.tostring(element))
else:
return ElementTree.tostring(element, encoding = "unicode") | python | {
"resource": ""
} |
q259696 | ResourceBindingHandler.bind | validation | def bind(self, stream, resource):
"""Bind to a resource.
[initiating entity only]
:Parameters:
- `resource`: the resource name to bind to.
:Types:
- `resource`: `unicode`
XMPP stream is authenticated for bare JID only. To use
the full JID it must be bound to a resource.
"""
self.stream = stream
stanza = Iq(stanza_type = "set")
payload = ResourceBindingPayload(resource = resource)
stanza.set_payload(payload)
self.stanza_processor.set_response_handlers(stanza,
self._bind_success, self._bind_error)
stream.send(stanza)
stream.event(BindingResourceEvent(resource)) | python | {
"resource": ""
} |
q259697 | ResourceBindingHandler._bind_success | validation | def _bind_success(self, stanza):
"""Handle resource binding success.
[initiating entity only]
:Parameters:
- `stanza`: <iq type="result"/> stanza received.
Set `streambase.StreamBase.me` to the full JID negotiated."""
# pylint: disable-msg=R0201
payload = stanza.get_payload(ResourceBindingPayload)
jid = payload.jid
if not jid:
raise BadRequestProtocolError(u"<jid/> element mising in"
" the bind response")
self.stream.me = jid
self.stream.event(AuthorizedEvent(self.stream.me)) | python | {
"resource": ""
} |
q259698 | serialize | validation | def serialize(element):
"""Serialize an XMPP element.
Utility function for debugging or logging.
:Parameters:
- `element`: the element to serialize
:Types:
- `element`: :etree:`ElementTree.Element`
:Return: serialized element
:Returntype: `unicode`
"""
if getattr(_THREAD, "serializer", None) is None:
_THREAD.serializer = XMPPSerializer("jabber:client")
_THREAD.serializer.emit_head(None, None)
return _THREAD.serializer.emit_stanza(element) | python | {
"resource": ""
} |
q259699 | XMPPSerializer.add_prefix | validation | def add_prefix(self, namespace, prefix):
"""Add a new namespace prefix.
If the root element has not yet been emitted the prefix will
be declared there, otherwise the prefix will be declared on the
top-most element using this namespace in every stanza.
:Parameters:
- `namespace`: the namespace URI
- `prefix`: the prefix string
:Types:
- `namespace`: `unicode`
- `prefix`: `unicode`
"""
if prefix == "xml" and namespace != XML_NS:
raise ValueError, "Cannot change 'xml' prefix meaning"
self._prefixes[namespace] = prefix | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.