XML Stream#

class slixmpp.xmlstream.xmlstream.XMLStream(host='', port=0)[source]#

An XML stream connection manager and event dispatcher.

The XMLStream class abstracts away the issues of establishing a connection with a server and sending and receiving XML “stanzas”. A stanza is a complete XML element that is a direct child of a root document element. Two streams are used, one for each communication direction, over the same socket. Once the connection is closed, both streams should be complete and valid XML documents.

Three types of events are provided to manage the stream:
Stream:

Triggered based on received stanzas, similar in concept to events in a SAX XML parser.

Custom:

Triggered manually.

Scheduled:

Triggered based on time delays.

Typically, stanzas are first processed by a stream event handler which will then trigger custom events to continue further processing, especially since custom event handlers may run in individual threads.

Parameters:
  • socket – Use an existing socket for the stream. Defaults to None to generate a new socket.

  • host (string) – The name of the target server.

  • port (int) – The port to use for the connection. Defaults to 0.

abort()[source]#

Forcibly close the connection

Return type:

None

add_event_handler(name, pointer, disposable=False)[source]#

Add a custom event handler that will be executed whenever its event is manually triggered.

Parameters:
  • name (str) – The name of the event that will trigger this handler.

  • pointer (Callable[..., Any]) – The function to execute.

  • disposable (bool) – If set to True, the handler will be discarded after one use. Defaults to False.

Return type:

None

add_filter(mode, handler, order=None)[source]#

Add a filter for incoming or outgoing stanzas.

These filters are applied before incoming stanzas are passed to any handlers, and before outgoing stanzas are put in the send queue.

Each filter must accept a single stanza, and return either a stanza or None. If the filter returns None, then the stanza will be dropped from being processed for events or from being sent.

Parameters:
  • mode (Literal['in', 'out', 'out_sync']) – One of 'in' or 'out'.

  • handler (Callable[[StanzaBase], Optional[StanzaBase]]) – The filter function.

  • order (int) – The position to insert the filter in the list of active filters.

Return type:

None

address: Tuple[str, int]#

The desired, or actual, address of the connected server.

ca_certs: Union[Path, Iterable[Path], None]#

Path to a file containing certificates for verifying the server SSL certificate. A non-None value will trigger certificate checking.

Note

On Mac OS X, certificates in the system keyring will be consulted, even if they are not in the provided file.

cancel_connection_attempt()[source]#

Immediately cancel the current create_connection() Future. This is useful when a client using slixmpp tries to connect on flaky networks, where sometimes a connection just gets lost and it needs to reconnect while the attempt is still ongoing.

Return type:

None

certfile: Optional[str]#

Path to a file containing a client certificate to use for authenticating via SASL EXTERNAL. If set, there must also be a corresponding :attr:keyfile value.

ciphers: Optional[str]#

The list of accepted ciphers, in OpenSSL Format. It might be useful to override it for improved security over the python defaults.

configure_dns(resolver, domain=None, port=None)[source]#

Configure and set options for a Resolver instance, and other DNS related tasks. For example, you can also check getaddrinfo() to see if you need to call out to libresolv.so.2 to run res_init().

Meant to be overridden.

Parameters:
  • resolver (Any) – A Resolver instance or None if dnspython is not installed.

  • domain (Optional[str]) – The initial domain under consideration.

  • port (Optional[int]) – The initial port under consideration.

Return type:

None

configure_socket()[source]#

Set timeout and other options for self.socket.

Meant to be overridden.

Return type:

None

connect(host='', port=0, use_ssl=None, force_starttls=None, disable_starttls=None)[source]#

Create a new socket and connect to the server.

Parameters:
  • host (str) – The name of the desired server for the connection.

  • port (int) – Port to connect to on the server.

  • use_ssl (Optional[bool]) – Flag indicating if SSL should be used by connecting directly to a port using SSL. If it is False, the connection will be upgraded to SSL/TLS later, using STARTTLS. Only use this value for old servers that have specific port for SSL/TLS

  • force_starttls (Optional[bool]) – If True, the connection will be aborted if the server does not initiate a STARTTLS negotiation. If None, the connection will be upgraded to TLS only if the server initiate the STARTTLS negotiation, otherwise it will connect in clear. If False it will never upgrade to TLS, even if the server provides it. Use this for example if you’re on localhost

Return type:

None

connection_lost(exception)[source]#

On any kind of disconnection, initiated by us or not. This signals the closure of the TCP connection

Return type:

None

connection_made(transport)[source]#

Called when the TCP connection has been established with the server

Return type:

None

data_received(data)[source]#

Called when incoming data is received on the socket.

We feed that data to the parser and the see if this produced any XML event. This could trigger one or more event (a stanza is received, the stream is opened, etc).

Return type:

None

default_domain: str#

The domain to try when querying DNS records.

default_ns: str#

The default namespace of the stream content, not of the stream wrapper it

default_port: int#

The default port to return when querying DNS records.

del_event_handler(name, pointer)[source]#

Remove a function as a handler for an event.

Parameters:
  • name (str) – The name of the event.

  • pointer (Callable[..., Any]) – The function to remove as a handler.

Return type:

None

del_filter(mode, handler)[source]#

Remove an incoming or outgoing filter.

Return type:

None

disconnect(wait=2.0, reason=None, ignore_send_queue=False)[source]#

Close the XML stream and wait for an acknowldgement from the server for at most wait seconds. After the given number of seconds has passed without a response from the server, or when the server successfully responds with a closure of its own stream, abort() is called. If wait is 0.0, this will call abort() directly without closing the stream.

Does nothing but trigger the disconnected event if we are not connected.

Parameters:
  • wait (Union[float, int]) – Time to wait for a response from the server.

  • reason (Optional[str]) – An optional reason for the disconnect.

  • ignore_send_queue (bool) – Boolean to toggle if we want to ignore the in-flight stanzas and disconnect immediately.

Return type:

Future

Returns:

A future that ends when all code involved in the disconnect has ended

disconnect_reason: Optional[str]#

The reason why we are disconnecting from the server

disconnected: Future#

An asyncio Future being done when the stream is disconnected.

dns_service: Optional[str]#

The service name to check with DNS SRV records. For example, setting this to 'xmpp-client' would query the _xmpp-client._tcp service.

end_session_on_disconnect: bool#

Flag for controlling if the session can be considered ended if the connection is terminated.

eof_received()[source]#

When the TCP connection is properly closed by the remote end

Return type:

None

event(name, data={})[source]#

Manually trigger a custom event. Coroutine handlers are wrapped into a future and sent into the event loop for their execution, and not awaited.

Parameters:
  • name (str) – The name of the event to trigger.

  • data (Any) – Data that will be passed to each event handler. Defaults to an empty dictionary, but is usually a stanza object.

Return type:

None

async event_async(name, data={})[source]#

Manually trigger a custom event, but await coroutines immediately.

This event generator should only be called in situations when in-order processing of events is important, such as features handling.

Parameters:
  • name (str) – The name of the event to trigger.

  • data (Any) – Data that will be passed to each event handler. Defaults to an empty dictionary, but is usually a stanza object.

Return type:

None

event_handled(name)[source]#

Returns the number of registered handlers for an event.

Parameters:

name (str) – The name of the event to check.

Return type:

int

event_handler(event, handler)[source]#

Context manager that adds then removes an event handler.

Return type:

Generator[None, None, None]

exception(exception)[source]#

Process an unknown exception.

Meant to be overridden.

Parameters:

exception (Exception) – An unhandled exception object.

Return type:

None

async get_dns_records(domain, port=None)[source]#

Get the DNS records for a domain.

Parameters:
  • domain (str) – The domain in question.

  • port (Optional[int]) – If the results don’t include a port, use this one.

Return type:

List[Tuple[str, str, int]]

get_ssl_context()[source]#

Get SSL context.

Return type:

SSLContext

incoming_filter(xml)[source]#

Filter incoming XML objects before they are processed.

Possible uses include remapping namespaces, or correcting elements from sources with incorrect behavior.

Meant to be overridden.

Return type:

Element

init_parser()[source]#

init the XML parser. The parser must always be reset for each new connexion

Return type:

None

keyfile: Optional[str]#

Path to a file containing the private key for the selected client certificate to use for authenticating via SASL EXTERNAL.

namespace_map: dict#

A mapping of XML namespaces to well-known prefixes.

new_id()[source]#

Generate and return a new stream ID in hexadecimal form.

Many stanzas, handlers, or matchers may require unique ID values. Using this method ensures that all new ID values are unique in this stream.

Return type:

str

process(*, forever=True, timeout=None)[source]#

Process all the available XMPP events (receiving or sending data on the socket(s), calling various registered callbacks, calling expired timers, handling signal events, etc). If timeout is None, this function will run forever. If timeout is a number, this function will return after the given time in seconds.

Will be removed in slixmpp 1.9.0

Deprecated:

1.8.0

Return type:

None

reconnect(wait=2.0, reason='Reconnecting')[source]#

Calls disconnect(), and once we are disconnected (after the timeout, or when the server acknowledgement is received), call connect()

Return type:

None

register_handler(handler, before=None, after=None)[source]#

Add a stream event handler that will be executed when a matching stanza is received.

Parameters:

handler (BaseHandler) – The BaseHandler derived object to execute.

Return type:

None

register_stanza(stanza_class)[source]#

Add a stanza object class as a known root stanza.

A root stanza is one that appears as a direct child of the stream’s root element.

Stanzas that appear as substanzas of a root stanza do not need to be registered here. That is done using register_stanza_plugin() from slixmpp.xmlstream.stanzabase.

Stanzas that are not registered will not be converted into stanza objects, but may still be processed using handlers and matchers.

Parameters:

stanza_class (Type[StanzaBase]) – The top-level stanza object’s class.

Return type:

None

remove_handler(name)[source]#

Remove any stream event handlers with the given name.

Parameters:

name (str) – The name of the handler.

Return type:

bool

remove_stanza(stanza_class)[source]#

Remove a stanza from being a known root stanza.

A root stanza is one that appears as a direct child of the stream’s root element.

Stanzas that are not registered will not be converted into stanza objects, but may still be processed using handlers and matchers.

Return type:

None

reschedule_connection_attempt()[source]#

Increase the exponential back-off and initate another background _connect_routine call to connect to the server.

Return type:

None

async run_filters()[source]#

Background loop that processes stanzas to send.

Return type:

None

schedule(name, seconds, callback, args=(), kwargs={}, repeat=False)[source]#

Schedule a callback function to execute after a given delay.

Parameters:
  • name (str) – A unique name for the scheduled callback.

  • seconds (int) – The time in seconds to wait before executing.

  • callback (Callable[..., None]) – A pointer to the function to execute.

  • args (Tuple[Any, ...]) – A tuple of arguments to pass to the function.

  • kwargs (Dict[Any, Any]) – A dictionary of keyword arguments to pass to the function.

  • repeat (bool) – Flag indicating if the scheduled event should be reset and repeat after executing.

Return type:

None

send(data, use_filters=True)[source]#

A wrapper for send_raw() for sending stanza objects.

Parameters:
  • data (Union[StanzaBase, str]) – The StanzaBase stanza to send on the stream.

  • use_filters (bool) – Indicates if outgoing filters should be applied to the given stanza data. Disabling filters is useful when resending stanzas. Defaults to True.

Return type:

None

send_raw(data)[source]#

Send raw data across the stream.

Parameters:

data (string) – Any bytes or utf-8 string value.

Return type:

None

send_xml(data)[source]#

Send an XML object on the stream

Parameters:

data (Element) – The Element XML object to send on the stream.

Return type:

None

start_stream_handler(xml)[source]#

Perform any initialization actions, such as handshakes, once the stream header has been sent.

Meant to be overridden.

Return type:

None

async start_tls()[source]#

Perform handshakes for TLS.

If the handshake is successful, the XML stream will need to be restarted.

Return type:

bool

The default closing tag for the stream element.

stream_header: str#

The default opening tag for the stream element.

stream_ns: str#

The namespace of the enveloping stream element.

use_aiodns: bool#

If set to True, allow using the dnspython DNS library if available. If set to False, the builtin DNS resolver will be used, even if dnspython is installed.

use_cdata: bool#

Use CDATA for escaping instead of XML entities. Defaults to False.

use_ipv6: bool#

If set to True, attempt to use IPv6.

use_ssl: bool#

Enable connecting to the server directly over SSL, in particular when the service provides two ports: one for non-SSL traffic and another for SSL traffic.

async wait_until(event, timeout=30)[source]#

Utility method to wake on the next firing of an event. (Registers a disposable handler on it)

Parameters:
  • event (str) – Event to wait on.

  • timeout (int) – Timeout

Raises:

asyncio.TimeoutError when the timeout is reached

Return type:

Any

whitespace_keepalive: bool#

If True, periodically send a whitespace character over the wire to keep the connection alive. Mainly useful for connections traversing NAT.

whitespace_keepalive_interval: int#

The default interval between keepalive signals when whitespace_keepalive is enabled.

wrap(coroutine)[source]#

Make a Future out of a coroutine with the current loop.

Parameters:

coroutine (Coroutine[None, None, TypeVar(T)]) – The coroutine to wrap.

Return type:

Future