summaryrefslogtreecommitdiff
path: root/sleekxmpp/componentxmpp.py
blob: e98ad50e78a98f25a8804ff1bd4c608196769b64 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
"""
    SleekXMPP: The Sleek XMPP Library
    Copyright (C) 2010  Nathanael C. Fritz
    This file is part of SleekXMPP.

    See the file LICENSE for copying permission.
"""

from __future__ import absolute_import

import logging
import base64
import sys
import hashlib

from sleekxmpp import plugins
from sleekxmpp import stanza
from sleekxmpp.basexmpp import BaseXMPP
from sleekxmpp.xmlstream import XMLStream, RestartStream
from sleekxmpp.xmlstream import StanzaBase, ET
from sleekxmpp.xmlstream.matcher import *
from sleekxmpp.xmlstream.handler import *


log = logging.getLogger(__name__)


class ComponentXMPP(BaseXMPP):

    """
    SleekXMPP's basic XMPP server component.

    Use only for good, not for evil.

    Methods:
        connect              -- Overrides XMLStream.connect.
        incoming_filter      -- Overrides XMLStream.incoming_filter.
        start_stream_handler -- Overrides XMLStream.start_stream_handler.
    """

    def __init__(self, jid, secret, host, port,
                 plugin_config={}, plugin_whitelist=[], use_jc_ns=False):
        """
        Arguments:
            jid              -- The JID of the component.
            secret           -- The secret or password for the component.
            host             -- The server accepting the component.
            port             -- The port used to connect to the server.
            plugin_config    -- A dictionary of plugin configurations.
            plugin_whitelist -- A list of desired plugins to load
                                when using register_plugins.
            use_js_ns        -- Indicates if the 'jabber:client' namespace
                                should be used instead of the standard
                                'jabber:component:accept' namespace.
                                Defaults to False.
        """
        if use_jc_ns:
            default_ns = 'jabber:client'
        else:
            default_ns = 'jabber:component:accept'
        BaseXMPP.__init__(self, jid, default_ns)

        self.auto_authorize = None
        self.stream_header = "<stream:stream %s %s to='%s'>" % (
                'xmlns="jabber:component:accept"',
                'xmlns:stream="%s"' % self.stream_ns,
                jid)
        self.stream_footer = "</stream:stream>"
        self.server_host = host
        self.server_port = port
        self.secret = secret

        self.plugin_config = plugin_config
        self.plugin_whitelist = plugin_whitelist
        self.is_component = True

        self.register_handler(
                Callback('Handshake',
                         MatchXPath('{jabber:component:accept}handshake'),
                         self._handle_handshake))
        self.add_event_handler('presence_probe',
                               self._handle_probe)

    def connect(self):
        """
        Connect to the server.

        Overrides XMLStream.connect.
        """
        log.debug("Connecting to %s:%s", self.server_host,
                                         self.server_port)
        return XMLStream.connect(self, self.server_host,
                                       self.server_port)

    def incoming_filter(self, xml):
        """
        Pre-process incoming XML stanzas by converting any 'jabber:client'
        namespaced elements to the component's default namespace.

        Overrides XMLStream.incoming_filter.

        Arguments:
            xml -- The XML stanza to pre-process.
        """
        if xml.tag.startswith('{jabber:client}'):
            xml.tag = xml.tag.replace('jabber:client', self.default_ns)

        # The incoming_filter call is only made on top level stanza
        # elements. So we manually continue filtering on sub-elements.
        for sub in xml:
            self.incoming_filter(sub)

        return xml

    def start_stream_handler(self, xml):
        """
        Once the streams are established, attempt to handshake
        with the server to be accepted as a component.

        Overrides BaseXMPP.start_stream_handler.

        Arguments:
            xml -- The incoming stream's root element.
        """
        BaseXMPP.start_stream_handler(self, xml)

        # Construct a hash of the stream ID and the component secret.
        sid = xml.get('id', '')
        pre_hash = '%s%s' % (sid, self.secret)
        if sys.version_info >= (3, 0):
            # Handle Unicode byte encoding in Python 3.
            pre_hash = bytes(pre_hash, 'utf-8')

        handshake = ET.Element('{jabber:component:accept}handshake')
        handshake.text = hashlib.sha1(pre_hash).hexdigest().lower()
        self.send_xml(handshake, now=True)

    def _handle_handshake(self, xml):
        """
        The handshake has been accepted.

        Arguments:
            xml -- The reply handshake stanza.
        """
        self.session_started_event.set()
        self.event("session_start")

    def _handle_probe(self, presence):
        pto = presence['to'].bare
        pfrom = presence['from'].bare
        self.roster[pto][pfrom].handle_probe(presence)