Debian Codegraph @

tx_xmpp/client.py

raw
1 # -*- test-case-name: tx_xmpp.test.test.test_client -*-
2 #
3 # Copyright (c) Ralph Meijer.
4 # See LICENSE for details.
5
6 """
7 XMPP Client support.
8
9 This module holds several improvements on top of Twisted's XMPP support
10 that should probably eventually move there.
11 """
12
13 from twisted.application import service
14 from twisted.internet import reactor
15 from twisted.names.srvconnect import SRVConnector
16 from twisted.words.protocols.jabber import client, sasl, xmlstream
17
18 from . import generic
19 from .subprotocols import StreamManager
20
21
22 class CheckAuthInitializer:
23 """
24 Check what authentication methods are available.
25 """
26
27 def __init__(self, xs):
28 self.xmlstream = xs
29
30 def initialize(self):
31 if (sasl.NS_XMPP_SASL, "mechanisms") in self.xmlstream.features:
32 inits = [
33 (sasl.SASLInitiatingInitializer, True),
34 (client.BindInitializer, True),
35 (client.SessionInitializer, False),
36 ]
37
38 for initClass, required in inits:
39 init = initClass(self.xmlstream)
40 init.required = required
41 self.xmlstream.initializers.append(init)
42 elif (client.NS_IQ_AUTH_FEATURE, "auth") in self.xmlstream.features:
43 self.xmlstream.initializers.append(client.IQAuthInitializer(self.xmlstream))
44 else:
45 raise Exception("No available authentication method found")
46
47
48 class HybridAuthenticator(xmlstream.ConnectAuthenticator):
49 """
50 Initializes an XmlStream connecting to an XMPP server as a Client.
51
52 This is similar to L{client.XMPPAuthenticator}, but also tries non-SASL
53 autentication.
54 """
55
56 namespace = "jabber:client"
57
58 def __init__(self, jid, password):
59 xmlstream.ConnectAuthenticator.__init__(self, jid.host)
60 self.jid = jid
61 self.password = password
62
63 def associateWithStream(self, xs):
64 xmlstream.ConnectAuthenticator.associateWithStream(self, xs)
65
66 tlsInit = xmlstream.TLSInitiatingInitializer(xs)
67 xs.initializers = [
68 client.CheckVersionInitializer(xs),
69 tlsInit,
70 CheckAuthInitializer(xs),
71 ]
72
73
74 def HybridClientFactory(jid, password):
75 """
76 Client factory for XMPP 1.0.
77
78 This is similar to L{client.XMPPClientFactory} but also tries non-SASL
79 autentication.
80 """
81
82 a = HybridAuthenticator(jid, password)
83 return xmlstream.XmlStreamFactory(a)
84
85
86 class XMPPClient(StreamManager, service.Service):
87 """
88 Service that initiates an XMPP client connection.
89 """
90
91 def __init__(self, jid, password, host=None, port=5222):
92 self.jid = jid
93 self.domain = jid.host.encode("idna")
94 self.host = host
95 self.port = port
96
97 factory = HybridClientFactory(jid, password)
98
99 StreamManager.__init__(self, factory)
100
101 def startService(self):
102 service.Service.startService(self)
103
104 self._connection = self._getConnection()
105
106 def stopService(self):
107 service.Service.stopService(self)
108
109 self.factory.stopTrying()
110 self._connection.disconnect()
111
112 def _authd(self, xs):
113 """
114 Called when the stream has been initialized.
115
116 Save the JID that we were assigned by the server, as the resource might
117 differ from the JID we asked for. This is stored on the authenticator
118 by its constituent initializers.
119 """
120 self.jid = self.factory.authenticator.jid
121 StreamManager._authd(self, xs)
122
123 def initializationFailed(self, reason):
124 """
125 Called when stream initialization has failed.
126
127 Stop the service (thereby disconnecting the current stream) and
128 raise the exception.
129 """
130 self.stopService()
131 reason.raiseException()
132
133 def _getConnection(self):
134 if self.host:
135 return reactor.connectTCP(self.host, self.port, self.factory)
136 else:
137 c = XMPPClientConnector(reactor, self.domain, self.factory)
138 c.connect()
139 return c
140
141
142 class DeferredClientFactory(generic.DeferredXmlStreamFactory):
143
144 def __init__(self, jid, password):
145 authenticator = client.XMPPAuthenticator(jid, password)
146 generic.DeferredXmlStreamFactory.__init__(self, authenticator)
147 self.streamManager = StreamManager(self)
148
149 def addHandler(self, handler):
150 """
151 Add a subprotocol handler to the stream manager.
152 """
153 self.streamManager.addHandler(handler)
154
155 def removeHandler(self, handler):
156 """
157 Add a subprotocol handler to the stream manager.
158 """
159 self.streamManager.removeHandler(handler)
160
161
162 class XMPPClientConnector(SRVConnector):
163 def __init__(self, reactor, domain, factory):
164 SRVConnector.__init__(self, reactor, "xmpp-client", domain, factory)
165
166 def pickServer(self):
167 host, port = SRVConnector.pickServer(self)
168
169 if not self.servers and not self.orderedServers:
170 # no SRV record, fall back..
171 port = 5222
172
173 return host, port
174
175
176 def clientCreator(factory):
177 domain = factory.authenticator.jid.host.encode("idna")
178 c = XMPPClientConnector(reactor, domain, factory)
179 c.connect()
180 return factory.deferred