class HashService(service.Service): """ The service component of the :xep:`300` support. This service registeres the features and allows to query the hash functions supported by us and a remote entity: .. automethod:: select_common_hashes """ ORDER_AFTER = [ disco.DiscoClient, disco.DiscoServer, ] hashes_feature = disco.register_feature(namespaces.xep0300_hashes2) def __init__(self, client, **kwargs): super().__init__(client, **kwargs) self._disco_client = self.dependencies[disco.DiscoClient] self._disco_server = self.dependencies[disco.DiscoServer] for feature in SUPPORTED_HASH_FEATURES: self._disco_server.register_feature(feature) @asyncio.coroutine def _shutdown(self): for feature in SUPPORTED_HASH_FEATURES: self._disco_server.unregister_feature(feature) yield from super()._shutdown() @asyncio.coroutine def select_common_hashes(self, other_entity): """ Return the list of algos supported by us and `other_entity`. The algorithms are represented by their :xep:`300` URNs (`urn:xmpp:hash-function-text-names:...`). :param other_entity: the address of another entity :type other_entity: :class:`aioxmpp.JID` :returns: the identifiers of the hash algorithms supported by both us and the other entity :rtype: :class:`set` :raises RuntimeError: if the other entity does not support the :xep:`300` feature nor does not publish hash functions URNs we support. Note: This assumes the protocol is supported if valid hash function features are detected, even if `urn:xmpp:hashes:2` is not listed as a feature. """ disco_info = yield from self._disco_client.query_info(other_entity) intersection = disco_info.features & SUPPORTED_HASH_FEATURES if (not intersection and namespaces.xep0300_hashes2 not in disco_info.features): raise RuntimeError( "Remote does not support the urn:xmpp:hashes:2 feature.") return intersection
class EntityCapsService(aioxmpp.service.Service): """ Make use and provide service discovery information in presence broadcasts. This service implements :xep:`0115` and :xep:`0390`, transparently. Besides loading the service, no interaction is required to get some of the benefits of :xep:`0115` and :xep:`0390`. Two additional things need to be done by users to get full support and performance: 1. To make sure that peers are always up-to-date with the current capabilities, it is required that users listen on the :meth:`on_ver_changed` signal and re-emit their current presence when it fires. .. note:: Keeping peers up-to-date is a MUST in :xep:`390`. The service takes care of attaching capabilities information on the outgoing stanza, using a stanza filter. .. warning:: :meth:`on_ver_changed` may be emitted at a considerable rate when services are loaded or certain features (such as PEP-based services) are configured. It is up to the application to limit the rate at which presences are sent for the sole purpose of updating peers with new capability information. 2. Users should use a process-wide :class:`Cache` instance and assign it to the :attr:`cache` of each :class:`.entitycaps.Service` they use. This improves performance by sharing (verified) hashes among :class:`Service` instances. In addition, the hashes should be saved and restored on shutdown/start of the process. See the :class:`Cache` for details. .. signal:: on_ver_changed The signal emits whenever the Capability Hashset of the local client changes. This happens when the set of features or identities announced in the :class:`.DiscoServer` changes. .. autoattribute:: cache .. autoattribute:: xep115_support .. autoattribute:: xep390_support .. versionchanged:: 0.8 This class was formerly known as :class:`aioxmpp.entitycaps.Service`. It is still available under that name, but the alias will be removed in 1.0. .. versionchanged:: 0.9 Support for :xep:`390` was added. """ ORDER_AFTER = { disco.DiscoClient, disco.DiscoServer, } NODE = "http://aioxmpp.zombofant.net/" on_ver_changed = aioxmpp.callbacks.Signal() def __init__(self, node, **kwargs): super().__init__(node, **kwargs) self.__current_keys = {} self._cache = Cache() self.disco_server = self.dependencies[disco.DiscoServer] self.disco_client = self.dependencies[disco.DiscoClient] self.__115 = caps115.Implementation(self.NODE) self.__390 = caps390.Implementation( aioxmpp.hashes.default_hash_algorithms) self.__active_hashsets = [] self.__key_users = collections.Counter() @property def xep115_support(self): """ Boolean to control whether :xep:`115` support is enabled or not. Defaults to :data:`True`. If set to false, inbound :xep:`115` capabilities will not be processed and no :xep:`115` capabilities will be emitted. .. note:: At some point, this will default to :data:`False` to save bandwidth. The exact release depends on the adoption of :xep:`390` and will be announced in time. If you depend on :xep:`115` support, set this boolean to :data:`True`. The attribute itself will not be removed until :xep:`115` support is removed from :mod:`aioxmpp` entirely, which is unlikely to happen any time soon. .. versionadded:: 0.9 """ return self._xep115_feature.enabled @xep115_support.setter def xep115_support(self, value): self._xep115_feature.enabled = value @property def xep390_support(self): """ Boolean to control whether :xep:`390` support is enabled or not. Defaults to :data:`True`. If set to false, inbound :xep:`390` Capability Hash Sets will not be processed and no Capability Hash Sets or Capability Nodes will be generated. The hash algortihms used for generating Capability Hash Sets are those from :data:`aioxmpp.hashes.default_hash_algorithms`. """ return self._xep390_feature.enabled @xep390_support.setter def xep390_support(self, value): self._xep390_feature.enabled = value @property def cache(self): """ The :class:`Cache` instance used for this :class:`Service`. Deleting this attribute will automatically create a new :class:`Cache` instance. The attribute can be used to share a single :class:`Cache` among multiple :class:`Service` instances. """ return self._cache @cache.setter def cache(self, v): self._cache = v @cache.deleter def cache(self): self._cache = Cache() @aioxmpp.service.depsignal(disco.DiscoServer, "on_info_changed") def _info_changed(self): self.logger.debug("info changed, scheduling re-calculation of version") asyncio.get_event_loop().call_soon(self.update_hash) @asyncio.coroutine def _shutdown(self): for group in self.__current_keys.values(): for key in group: self.disco_server.unmount_node(key.node) @asyncio.coroutine def query_and_cache(self, jid, key, fut): data = yield from self.disco_client.query_info( jid, node=key.node, require_fresh=True, no_cache=True, # the caps node is never queried by apps ) try: if key.verify(data): self.cache.add_cache_entry(key, data) fut.set_result(data) else: raise ValueError("hash mismatch") except ValueError as exc: fut.set_exception(exc) return data @asyncio.coroutine def lookup_info(self, jid, keys): for key in keys: try: info = yield from self.cache.lookup(key) except KeyError: continue self.logger.debug("found %s in cache", key) return info first_key = keys[0] self.logger.debug("using key %s to query peer", first_key) fut = self.cache.create_query_future(first_key) info = yield from self.query_and_cache(jid, first_key, fut) self.logger.debug("%s maps to %r", key, info) return info @aioxmpp.service.outbound_presence_filter def handle_outbound_presence(self, presence): if (presence.type_ == aioxmpp.structs.PresenceType.AVAILABLE and self.__active_hashsets): current_hashset = self.__active_hashsets[-1] try: keys = current_hashset[self.__115] except KeyError: pass else: self.__115.put_keys(keys, presence) try: keys = current_hashset[self.__390] except KeyError: pass else: self.__390.put_keys(keys, presence) return presence @aioxmpp.service.inbound_presence_filter def handle_inbound_presence(self, presence): keys = [] if self.xep390_support: keys.extend(self.__390.extract_keys(presence)) if self.xep115_support: keys.extend(self.__115.extract_keys(presence)) if keys: lookup_task = aioxmpp.utils.LazyTask( self.lookup_info, presence.from_, keys, ) self.disco_client.set_info_future(presence.from_, None, lookup_task) return presence def _push_hashset(self, node, hashset): if self.__active_hashsets and hashset == self.__active_hashsets[-1]: return False for group in hashset.values(): for key in group: if not self.__key_users[key.node]: self.disco_server.mount_node(key.node, node) self.__key_users[key.node] += 1 self.__active_hashsets.append(hashset) for expired in self.__active_hashsets[:-3]: for group in expired.values(): for key in group: self.__key_users[key.node] -= 1 if not self.__key_users[key.node]: self.disco_server.unmount_node(key.node) del self.__key_users[key.node] del self.__active_hashsets[:-3] return True def update_hash(self): node = disco.StaticNode.clone(self.disco_server) info = node.as_info_xso() new_hashset = {} if self.xep115_support: new_hashset[self.__115] = set(self.__115.calculate_keys(info)) if self.xep390_support: new_hashset[self.__390] = set(self.__390.calculate_keys(info)) self.logger.debug("new hashset=%r", new_hashset) if self._push_hashset(node, new_hashset): self.on_ver_changed() # declare those at the bottom so that on_ver_changed gets emitted when the # service is instantiated _xep115_feature = disco.register_feature(namespaces.xep0115_caps) _xep390_feature = disco.register_feature(namespaces.xep0390_caps)