Skip to content
Back to top
View this page

# XML Stream

class slixmpp.xmlstream.xmlstream.XMLStream(host='', port=0, ssl_context=None, loop=None)

  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()

    Forcibly close the connection

    Return type:

      `None`

  add_event_handler(name, pointer, disposable=False)

    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)

    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`], `StanzaBase` | `None`]) – The filter function.

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

    Return type:

      `None`

  ca_certs: `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()

    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: `str` | `None`

    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: `str` | `None`

    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)

    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 (`str` | `None`) – The initial domain under consideration.

      - port (`int` | `None`) – The initial port under consideration.

    Return type:

      `None`

  configure_socket()

    Set timeout and other options for self.socket.

    Meant to be overridden.

    Return type:

      `None`

  connect(host=None, port=None)

    Create a new socket and connect to the server.

    Parameters:

      - host (`str` | `None`) – The name of the desired server for the connection.

      - port (`int` | `None`) – Port to connect to on the server.

    Return type:

      `Future`

    Returns:

      A future on the current connection attempt

  connection_lost(exception)

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

    Return type:

      `None`

  connection_made(transport, send_event=True)

    Called when the TCP connection has been established with the server

    Return type:

      `None`

  custom_address: `Tuple`[`str`, `int`] | `None`

    A custom address to connect to that was provided to connect(). When using DNS lookups, this is not used. Once set, it will be re-used until connect() is called with no parameters (or both host and port set to None).

  data_received(data)

    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)

    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)

    Remove an incoming or outgoing filter.

    Return type:

      `None`

  disconnect(wait=2.0, reason=None, ignore_send_queue=False)

    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 (`float` | `int`) – Time to wait for a response from the server.

      - reason (`str` | `None`) – 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: `str` | `None`

    The reason why we are disconnecting from the server

  disconnected: `Future`

    An asyncio Future being done when the stream is disconnected.

  enable_direct_tls: `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.

  enable_plaintext: `bool`

    Enable connecting to the server using plaintext strongly not recommended (unless for localhost components)

  enable_starttls: `bool`

    Enable connecting to the server using STARTTLS (i.e. upgrading a clear connection once established).

  end_session_on_disconnect: `bool`

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

  eof_received()

    When the TCP connection is properly closed by the remote end

    Return type:

      `None`

  event(name, data={})

    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={})

    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)

    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)

    Context manager that adds then removes an event handler.

    Return type:

      `Generator`[`None`, `None`, `None`]

  exception(exception)

    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)

    Get the DNS records for a domain.

    Parameters:

      - domain (`str`) – The domain in question.

      - port (`int` | `None`) – If the results don’t include a port, use this one.

    Return type:

      `List`[`Tuple`[`str`, `str`, `str`, `int`]]

  get_ssl_context()

    Get SSL context.

    Return type:

      `SSLContext`

  incoming_filter(xml)

    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()

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

    Return type:

      `None`

  keyfile: `str` | `None`

    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()

    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`

  reconnect(wait=2.0, reason='Reconnecting')

    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)

    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)

    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)

    Remove any stream event handlers with the given name.

    Parameters:

      name (`str`) – The name of the handler.

    Return type:

      `bool`

  remove_stanza(stanza_class)

    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()

    Increase the exponential back-off and initiate another background _connect_loop call to connect to the server.

    Return type:

      `Future` | `None`

    Returns:

      A future on the next scheduled connection attempt.

  async run_filters()

    Background loop that processes stanzas to send.

    Return type:

      `None`

  schedule(name, seconds, callback, args=(), kwargs={}, repeat=False)

    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)

    A wrapper for `send_raw()` for sending stanza objects.

    Parameters:

      - data (`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)

    Send raw data across the stream.

    Parameters:

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

    Return type:

      `None`

  send_xml(data)

    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)

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

    Meant to be overridden.

    Return type:

      `None`

  async start_tls()

    Perform handshakes for TLS.

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

    Return type:

      `bool`

  starttls_services: `Set`[`str`]

    List of DNS SRV services records which map to STARTTLS services

  stream_footer: `str`

    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.

  tls_services: `Set`[`str`]

    List of DNS SRV services records which map to TLS services

  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.

  async wait_until(event, timeout=30)

    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)

    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`