Debian Codegraph @

tx_xmpp/generic.py

raw
1 # -*- test-case-name: tx_xmpp.test.test.test_generic -*-
2 #
3 # Copyright (c) Ralph Meijer.
4 # See LICENSE for details.
5
6 """
7 Generic XMPP protocol helpers.
8 """
9
10 from zope.interface import implementer
11
12 from twisted.internet import defer, protocol
13 from twisted.python import reflect
14 from twisted.words.protocols.jabber import error, jid, xmlstream
15 from twisted.words.protocols.jabber.xmlstream import toResponse
16 from twisted.words.xish import domish, utility
17 from twisted.words.xish.xmlstream import BootstrapMixin
18
19 from .itx_xmpp import IDisco
20 from .subprotocols import XMPPHandler
21
22 IQ_GET = '/iq[@type="get"]'
23 IQ_SET = '/iq[@type="set"]'
24
25 NS_VERSION = "jabber:iq:version"
26 VERSION = IQ_GET + '/query[@xmlns="' + NS_VERSION + '"]'
27
28
29 def parseXml(string):
30 """
31 Parse serialized XML into a DOM structure.
32
33 @param string: The serialized XML to be parsed, UTF-8 encoded.
34 @type string: L{str}.
35 @return: The DOM structure, or C{None} on empty or incomplete input.
36 @rtype: L{domish.Element}
37 """
38 roots = []
39 results = []
40 elementStream = domish.elementStream()
41 elementStream.DocumentStartEvent = roots.append
42 elementStream.ElementEvent = lambda elem: roots[0].addChild(elem)
43 elementStream.DocumentEndEvent = lambda: results.append(roots[0])
44 elementStream.parse(string)
45 return results and results[0] or None
46
47
48 def stripNamespace(rootElement):
49 namespace = rootElement.uri
50
51 def strip(element):
52 if element.uri == namespace:
53 element.uri = None
54 if element.defaultUri == namespace:
55 element.defaultUri = None
56 for child in element.elements():
57 strip(child)
58
59 if namespace is not None:
60 strip(rootElement)
61
62 return rootElement
63
64
65 class FallbackHandler(XMPPHandler):
66 """
67 XMPP subprotocol handler that catches unhandled iq requests.
68
69 Unhandled iq requests are replied to with a service-unavailable stanza
70 error.
71 """
72
73 def connectionInitialized(self):
74 self.xmlstream.addObserver(IQ_SET, self.iqFallback, -1)
75 self.xmlstream.addObserver(IQ_GET, self.iqFallback, -1)
76
77 def iqFallback(self, iq):
78 if iq.handled == True:
79 return
80
81 reply = error.StanzaError("service-unavailable")
82 self.xmlstream.send(reply.toResponse(iq))
83
84
85 @implementer(IDisco)
86 class VersionHandler(XMPPHandler):
87 """
88 XMPP subprotocol handler for XMPP Software Version.
89
90 This protocol is described in
91 U{XEP-0092<http://xmpp.org/extensions/xep-0092.html>}.
92 """
93
94 def __init__(self, name, version):
95 self.name = name
96 self.version = version
97
98 def connectionInitialized(self):
99 self.xmlstream.addObserver(VERSION, self.onVersion)
100
101 def onVersion(self, iq):
102 response = toResponse(iq, "result")
103
104 query = response.addElement((NS_VERSION, "query"))
105 query.addElement("name", content=self.name)
106 query.addElement("version", content=self.version)
107 self.send(response)
108
109 iq.handled = True
110
111 def getDiscoInfo(self, requestor, target, nodeIdentifier=""):
112 info = set()
113
114 if not nodeIdentifier:
115 from . import disco
116
117 info.add(disco.DiscoFeature(NS_VERSION))
118
119 return defer.succeed(info)
120
121 def getDiscoItems(self, requestor, target, nodeIdentifier=""):
122 return defer.succeed([])
123
124
125 class XmlPipe:
126 """
127 XML stream pipe.
128
129 Connects two objects that communicate stanzas through an XML stream like
130 interface. Each of the ends of the pipe (sink and source) can be used to
131 send XML stanzas to the other side, or add observers to process XML stanzas
132 that were sent from the other side.
133
134 XML pipes are usually used in place of regular XML streams that are
135 transported over TCP. This is the reason for the use of the names source
136 and sink for both ends of the pipe. The source side corresponds with the
137 entity that initiated the TCP connection, whereas the sink corresponds with
138 the entity that accepts that connection. In this object, though, the source
139 and sink are treated equally.
140
141 Unlike Jabber
142 L{XmlStream<twisted.words.protocols.jabber.xmlstream.XmlStream>}s, the sink
143 and source objects are assumed to represent an eternal connected and
144 initialized XML stream. As such, events corresponding to connection,
145 disconnection, initialization and stream errors are not dispatched or
146 processed.
147
148 @ivar source: Source XML stream.
149 @ivar sink: Sink XML stream.
150 """
151
152 def __init__(self):
153 self.source = utility.EventDispatcher()
154 self.sink = utility.EventDispatcher()
155 self.source.send = lambda obj: self.sink.dispatch(obj)
156 self.sink.send = lambda obj: self.source.dispatch(obj)
157
158
159 class Stanza:
160 """
161 Abstract representation of a stanza.
162
163 @ivar sender: The sending entity.
164 @type sender: L{jid.JID}
165 @ivar recipient: The receiving entity.
166 @type recipient: L{jid.JID}
167 """
168
169 recipient = None
170 sender = None
171 stanzaKind = None
172 stanzaID = None
173 stanzaType = None
174
175 def __init__(self, recipient=None, sender=None):
176 self.recipient = recipient
177 self.sender = sender
178
179 @classmethod
180 def fromElement(Class, element):
181 """
182 Create a stanza from a L{domish.Element}.
183 """
184 stanza = Class()
185 stanza.parseElement(element)
186 return stanza
187
188 def parseElement(self, element):
189 """
190 Parse the stanza element.
191
192 This is called with the stanza's element when a L{Stanza} is
193 created using L{fromElement}. It parses the stanza's core attributes
194 (addressing, type and id), strips the namespace from the stanza
195 element for easier transport across streams and passes on
196 child elements for further parsing.
197
198 Child element parsers are defined by providing a C{childParsers}
199 attribute on a subclass, as a mapping from (URI, name) to the name
200 of the handler on C{self}. C{parseElement} will accumulate
201 C{childParsers} from its class hierarchy, iterate over the child
202 elements and pass it to matching handlers based on the child element's
203 URI and name. The special key of C{None} can be used to pass all
204 child elements to.
205 """
206 if element.hasAttribute("from"):
207 self.sender = jid.internJID(element["from"])
208 if element.hasAttribute("to"):
209 self.recipient = jid.internJID(element["to"])
210 self.stanzaType = element.getAttribute("type")
211 self.stanzaID = element.getAttribute("id")
212
213 # Save element
214 stripNamespace(element)
215 self.element = element
216
217 # accumulate all childHandlers in the class hierarchy of Class
218 handlers = {}
219 reflect.accumulateClassDict(self.__class__, "childParsers", handlers)
220
221 for child in element.elements():
222 try:
223 handler = handlers[child.uri, child.name]
224 except KeyError:
225 try:
226 handler = handlers[None]
227 except KeyError:
228 continue
229
230 getattr(self, handler)(child)
231
232 def toElement(self):
233 element = domish.Element((None, self.stanzaKind))
234 if self.sender is not None:
235 element["from"] = self.sender.full()
236 if self.recipient is not None:
237 element["to"] = self.recipient.full()
238 if self.stanzaType:
239 element["type"] = self.stanzaType
240 if self.stanzaID:
241 element["id"] = self.stanzaID
242 return element
243
244
245 class ErrorStanza(Stanza):
246
247 def parseElement(self, element):
248 Stanza.parseElement(self, element)
249 self.exception = error.exceptionFromStanza(element)
250
251
252 class Request(Stanza):
253 """
254 IQ request stanza.
255
256 This is a base class for IQ get or set stanzas, to be used with
257 L{tx_xmpp.subprotocols.StreamManager.request}.
258 """
259
260 stanzaKind = "iq"
261 stanzaType = "get"
262 timeout = None
263
264 childParsers = {None: "parseRequest"}
265
266 def __init__(self, recipient=None, sender=None, stanzaType=None):
267 Stanza.__init__(self, recipient=recipient, sender=sender)
268 if stanzaType is not None:
269 self.stanzaType = stanzaType
270
271 def parseRequest(self, element):
272 """
273 Called with the request's child element for parsing.
274
275 When a request instance is created using L{fromElement}, this method
276 is called with the child element of the iq. Override this method for
277 parsing the request's payload.
278 """
279
280 def toElement(self):
281 element = Stanza.toElement(self)
282
283 if not self.stanzaID:
284 element.addUniqueId()
285 self.stanzaID = element["id"]
286
287 return element
288
289
290 class DeferredXmlStreamFactory(BootstrapMixin, protocol.ClientFactory):
291 protocol = xmlstream.XmlStream
292
293 def __init__(self, authenticator):
294 BootstrapMixin.__init__(self)
295
296 self.authenticator = authenticator
297
298 deferred = defer.Deferred()
299 self.deferred = deferred
300 self.addBootstrap(xmlstream.STREAM_AUTHD_EVENT, self.deferred.callback)
301 self.addBootstrap(xmlstream.INIT_FAILED_EVENT, deferred.errback)
302
303 def buildProtocol(self, addr):
304 """
305 Create an instance of XmlStream.
306
307 A new authenticator instance will be created and passed to the new
308 XmlStream. Registered bootstrap event observers are installed as well.
309 """
310 xs = self.protocol(self.authenticator)
311 xs.factory = self
312 self.installBootstraps(xs)
313 return xs
314
315 def clientConnectionFailed(self, connector, reason):
316 self.deferred.errback(reason)