Debian Codegraph @

tx_xmpp/subprotocols.py

raw
1 # -*- test-case-name: tx_xmpp.test.test_subprotocols -*-
2 #
3 # Copyright (c) Twisted Matrix Laboratories.
4 # See LICENSE for details.
5
6 """
7 XMPP subprotocol support.
8 """
9
10 from zope.interface import implementer
11
12 from twisted.internet import defer
13 from twisted.internet.error import ConnectionDone
14 from twisted.python import failure, log
15 from twisted.words.protocols.jabber import error, ijabber, xmlstream
16 from twisted.words.protocols.jabber.xmlstream import toResponse
17 from twisted.words.protocols.jabber.xmlstream import XMPPHandlerCollection
18 from twisted.words.xish import xpath
19 from twisted.words.xish.domish import IElement
20
21
22 @implementer(ijabber.IXMPPHandler)
23 class XMPPHandler:
24 """
25 XMPP protocol handler.
26
27 Classes derived from this class implement (part of) one or more XMPP
28 extension protocols, and are referred to as a subprotocol implementation.
29 """
30
31 def __init__(self):
32 self.parent = None
33 self.xmlstream = None
34
35 def setHandlerParent(self, parent):
36 self.parent = parent
37 self.parent.addHandler(self)
38
39 def disownHandlerParent(self, parent):
40 self.parent.removeHandler(self)
41 self.parent = None
42
43 def makeConnection(self, xs):
44 self.xmlstream = xs
45 self.connectionMade()
46
47 def connectionMade(self):
48 """
49 Called after a connection has been established.
50
51 Can be overridden to perform work before stream initialization.
52 """
53
54 def connectionInitialized(self):
55 """
56 The XML stream has been initialized.
57
58 Can be overridden to perform work after stream initialization, e.g. to
59 set up observers and start exchanging XML stanzas.
60 """
61
62 def connectionLost(self, reason):
63 """
64 The XML stream has been closed.
65
66 This method can be extended to inspect the C{reason} argument and
67 act on it.
68 """
69 self.xmlstream = None
70
71 def send(self, obj):
72 """
73 Send data over the managed XML stream.
74
75 @note: The stream manager maintains a queue for data sent using this
76 method when there is no current initialized XML stream. This
77 data is then sent as soon as a new stream has been established
78 and initialized. Subsequently, L{connectionInitialized} will be
79 called again. If this queueing is not desired, use C{send} on
80 C{self.xmlstream}.
81
82 @param obj: data to be sent over the XML stream. This is usually an
83 object providing L{domish.IElement}, or serialized XML. See
84 L{xmlstream.XmlStream} for details.
85 """
86 self.parent.send(obj)
87
88 def request(self, request):
89 """
90 Send an IQ request and track the response.
91
92 This passes the request to the parent for sending and response
93 tracking.
94
95 @see: L{StreamManager.request}.
96 """
97 return self.parent.request(request)
98
99
100 class StreamManager(XMPPHandlerCollection):
101 """
102 Business logic representing a managed XMPP connection.
103
104 This maintains a single XMPP connection and provides facilities for packet
105 routing and transmission. Business logic modules are objects providing
106 L{IXMPPHandler} (like subclasses of L{XMPPHandler}), and added
107 using L{addHandler}.
108
109 @ivar xmlstream: currently managed XML stream
110 @type xmlstream: L{XmlStream}
111 @ivar logTraffic: if true, log all traffic.
112 @type logTraffic: L{bool}
113 @ivar _initialized: Whether the stream represented by L{xmlstream} has
114 been initialized. This is used when caching outgoing
115 stanzas.
116 @type _initialized: L{bool}
117 @ivar _packetQueue: internal buffer of unsent data. See L{send} for details.
118 @type _packetQueue: L{list}
119 @ivar timeout: Default IQ request timeout in seconds.
120 @type timeout: L{int}
121 @ivar _reactor: A provider of L{IReactorTime} to track timeouts.
122 """
123
124 timeout = None
125 _reactor = None
126
127 logTraffic = False
128
129 def __init__(self, factory, reactor=None):
130 """
131 Construct a stream manager.
132
133 @param factory: The stream factory to connect with.
134 @param reactor: A provider of L{IReactorTime} to track timeouts.
135 If not provided, the global reactor will be used.
136 """
137 XMPPHandlerCollection.__init__(self)
138 self.xmlstream = None
139 self._packetQueue = []
140 self._initialized = False
141
142 factory.addBootstrap(xmlstream.STREAM_CONNECTED_EVENT, self._connected)
143 factory.addBootstrap(xmlstream.STREAM_AUTHD_EVENT, self._authd)
144 factory.addBootstrap(xmlstream.INIT_FAILED_EVENT, self.initializationFailed)
145 factory.addBootstrap(xmlstream.STREAM_END_EVENT, self._disconnected)
146 self.factory = factory
147
148 if reactor is None:
149 from twisted.internet import reactor
150 self._reactor = reactor
151
152 # Set up IQ response tracking
153 self._iqDeferreds = {}
154
155 def addHandler(self, handler):
156 """
157 Add protocol handler.
158
159 When an XML stream has already been established, the handler's
160 C{connectionInitialized} will be called to get it up to speed.
161 """
162 XMPPHandlerCollection.addHandler(self, handler)
163
164 # get protocol handler up to speed when a connection has already
165 # been established
166 if self.xmlstream:
167 handler.makeConnection(self.xmlstream)
168 if self._initialized:
169 handler.connectionInitialized()
170
171 def _connected(self, xs):
172 """
173 Called when the transport connection has been established.
174
175 Here we optionally set up traffic logging (depending on L{logTraffic})
176 and call each handler's C{makeConnection} method with the L{XmlStream}
177 instance.
178 """
179
180 def logDataIn(buf):
181 log.msg("RECV: %r" % buf)
182
183 def logDataOut(buf):
184 log.msg("SEND: %r" % buf)
185
186 if self.logTraffic:
187 xs.rawDataInFn = logDataIn
188 xs.rawDataOutFn = logDataOut
189
190 self.xmlstream = xs
191
192 for e in list(self):
193 e.makeConnection(xs)
194
195 def _authd(self, xs):
196 """
197 Called when the stream has been initialized.
198
199 Send out cached stanzas and call each handler's
200 C{connectionInitialized} method.
201 """
202
203 xs.addObserver('/iq[@type="result"]', self._onIQResponse)
204 xs.addObserver('/iq[@type="error"]', self._onIQResponse)
205
206 # Flush all pending packets
207 for p in self._packetQueue:
208 xs.send(p)
209 self._packetQueue = []
210 self._initialized = True
211
212 # Notify all child services which implement
213 # the IService interface
214 for e in list(self):
215 e.connectionInitialized()
216
217 def initializationFailed(self, reason):
218 """
219 Called when stream initialization has failed.
220
221 Stream initialization has halted, with the reason indicated by
222 C{reason}. It may be retried by calling the authenticator's
223 C{initializeStream}. See the respective authenticators for details.
224
225 @param reason: A failure instance indicating why stream initialization
226 failed.
227 @type reason: L{failure.Failure}
228 """
229
230 def _disconnected(self, reason):
231 """
232 Called when the stream has been closed.
233
234 From this point on, the manager doesn't interact with the
235 L{XmlStream} anymore and notifies each handler that the connection
236 was lost by calling its C{connectionLost} method.
237 """
238 self.xmlstream = None
239 self._initialized = False
240
241 # Twisted versions before 11.0 passed an XmlStream here.
242 if not hasattr(reason, "trap"):
243 reason = failure.Failure(ConnectionDone())
244
245 # Notify all child services which implement
246 # the IService interface
247 for e in list(self):
248 e.connectionLost(reason)
249
250 # This errbacks all deferreds of iq's for which no response has
251 # been received with a L{ConnectionLost} failure. Otherwise, the
252 # deferreds will never be fired.
253 iqDeferreds = self._iqDeferreds
254 self._iqDeferreds = {}
255 for d in iqDeferreds.values():
256 d.errback(reason)
257
258 def _onIQResponse(self, iq):
259 """
260 Handle iq response by firing associated deferred.
261 """
262 try:
263 d = self._iqDeferreds[iq["id"]]
264 except KeyError:
265 return
266
267 del self._iqDeferreds[iq["id"]]
268 iq.handled = True
269 if iq["type"] == "error":
270 d.errback(error.exceptionFromStanza(iq))
271 else:
272 d.callback(iq)
273
274 def send(self, obj):
275 """
276 Send data over the XML stream.
277
278 When there is no established XML stream, the data is queued and sent
279 out when a new XML stream has been established and initialized.
280
281 @param obj: data to be sent over the XML stream. See
282 L{xmlstream.XmlStream.send} for details.
283 """
284 if self._initialized:
285 self.xmlstream.send(obj)
286 else:
287 self._packetQueue.append(obj)
288
289 def request(self, request):
290 """
291 Send an IQ request and track the response.
292
293 A request is an IQ L{generic.Stanza} of type C{'get'} or C{'set'}. It
294 will have its C{toElement} called to render to a
295 L{Element<twisted.words.xish.domish.Element>} which is then sent out
296 over the current stream. If there is no such stream (yet), it is queued
297 and sent whenever a connection is established and initialized, just
298 like L{send}.
299
300 If the request doesn't have an identifier, it will be assigned a fresh
301 one, so the response can be tracked.
302
303 The deferred that is returned will fire with the
304 L{Element<twisted.words.xish.domish.Element>} representation of the
305 response if it is a result iq. If the response is an error iq, a
306 corresponding L{error.StanzaError} will be errbacked.
307
308 If the connection is closed before a response was received, the deferred
309 will be errbacked with the reason failure.
310
311 A request may also have a timeout, either by setting a default timeout
312 in L{StreamManager}'s C{timeout} attribute or on the C{timeout}
313 attribute of the request.
314
315 @param request: The IQ request.
316 @type request: L{generic.Request}
317 """
318 if request.stanzaKind != "iq" or request.stanzaType not in ("get", "set"):
319 return defer.fail(ValueError("Not a request"))
320
321 element = request.toElement()
322
323 # Make sure we have a trackable id on the stanza
324 if not request.stanzaID:
325 element.addUniqueId()
326 request.stanzaID = element["id"]
327
328 # Set up iq response tracking
329 d = defer.Deferred()
330 self._iqDeferreds[element["id"]] = d
331
332 timeout = getattr(request, "timeout", self.timeout)
333
334 if timeout is not None:
335
336 def onTimeout():
337 del self._iqDeferreds[element["id"]]
338 d.errback(xmlstream.TimeoutError("IQ timed out"))
339
340 call = self._reactor.callLater(timeout, onTimeout)
341
342 def cancelTimeout(result):
343 if call.active():
344 call.cancel()
345
346 return result
347
348 d.addBoth(cancelTimeout)
349 self.send(element)
350 return d
351
352
353 class IQHandlerMixin:
354 """
355 XMPP subprotocol mixin for handle incoming IQ stanzas.
356
357 This matches up the iq with XPath queries to call methods on itself,
358 wrapping the call so that exceptions result in proper error responses,
359 or, when succesful will reply with a response with optional payload.
360
361 Derivatives of this class must provide an
362 L{XmlStream<twisted.words.protocols.jabber.xmlstream.XmlStream>} instance
363 in its C{xmlstream} attribute.
364
365 The optional payload is taken from the result of the handler and is
366 expected to be a child or a list of childs.
367
368 If an exception is raised, or the deferred has its errback called,
369 the exception is checked for being a L{error.StanzaError}. If so,
370 an error response is sent. Any other exception will cause a error
371 response of C{internal-server-error} to be sent.
372
373 A typical way to use this mixin, is to set up L{xpath} observers on the
374 C{xmlstream} to call handleRequest, for example in an overridden
375 L{XMPPHandler.connectionMade}. It is likely a good idea to only listen for
376 incoming iq get and/org iq set requests, and not for any iq, to prevent
377 hijacking incoming responses to outgoing iq requests. An example:
378
379 >>> QUERY_ROSTER = "/query[@xmlns='jabber:iq:roster']"
380 >>> class MyHandler(XMPPHandler, IQHandlerMixin):
381 ... iqHandlers = {"/iq[@type='get']" + QUERY_ROSTER: 'onRosterGet',
382 ... "/iq[@type='set']" + QUERY_ROSTER: 'onRosterSet'}
383 ... def connectionMade(self):
384 ... self.xmlstream.addObserver(
385 ... "/iq[@type='get' or @type='set']" + QUERY_ROSTER,
386 ... self.handleRequest)
387 ... def onRosterGet(self, iq):
388 ... pass
389 ... def onRosterSet(self, iq):
390 ... pass
391
392 @cvar iqHandlers: Mapping from XPath queries (as a string) to the method
393 name that will handle requests that match the query.
394 @type iqHandlers: L{dict}
395 """
396
397 iqHandlers = None
398
399 def handleRequest(self, iq):
400 """
401 Find a handler and wrap the call for sending a response stanza.
402 """
403
404 def toResult(result, iq):
405 response = toResponse(iq, "result")
406
407 if result:
408 if IElement.providedBy(result):
409 response.addChild(result)
410 else:
411 for element in result:
412 response.addChild(element)
413
414 return response
415
416 def checkNotImplemented(failure):
417 failure.trap(NotImplementedError)
418 raise error.StanzaError("feature-not-implemented")
419
420 def fromStanzaError(failure, iq):
421 failure.trap(error.StanzaError)
422 return failure.value.toResponse(iq)
423
424 def fromOtherError(failure, iq):
425 log.msg("Unhandled error in iq handler:", isError=True)
426 log.err(failure)
427 return error.StanzaError("internal-server-error").toResponse(iq)
428
429 handler = None
430 for queryString, method in self.iqHandlers.items():
431 if xpath.internQuery(queryString).matches(iq):
432 handler = getattr(self, method)
433
434 if handler:
435 d = defer.maybeDeferred(handler, iq)
436 else:
437 d = defer.fail(NotImplementedError())
438
439 d.addCallback(toResult, iq)
440 d.addErrback(checkNotImplemented)
441 d.addErrback(fromStanzaError, iq)
442 d.addErrback(fromOtherError, iq)
443
444 d.addCallback(self.send)
445
446 iq.handled = True
447
448
449 __all__ = ["XMPPHandler", "StreamManager", "IQHandlerMixin"]