| 1 |
# -*- test-case-name: tx_xmpp.test.test.test_component -*- |
| 2 |
# |
| 3 |
# Copyright (c) Ralph Meijer. |
| 4 |
# See LICENSE for details. |
| 5 |
|
| 6 |
""" |
| 7 |
XMPP External Component utilities. |
| 8 |
""" |
| 9 |
|
| 10 |
from twisted.application import service |
| 11 |
from twisted.internet import reactor |
| 12 |
from twisted.python import log |
| 13 |
from twisted.words.protocols.jabber.jid import internJID as JID |
| 14 |
from twisted.words.protocols.jabber import component, error, xmlstream |
| 15 |
from twisted.words.xish import domish |
| 16 |
|
| 17 |
from .generic import XmlPipe |
| 18 |
from .subprotocols import StreamManager |
| 19 |
|
| 20 |
NS_COMPONENT_ACCEPT = "jabber:component:accept" |
| 21 |
|
| 22 |
|
| 23 |
class Component(StreamManager, service.Service): |
| 24 |
""" |
| 25 |
XMPP External Component service. |
| 26 |
|
| 27 |
This service is a XMPP stream manager that connects as an External |
| 28 |
Component to an XMPP server, as described in |
| 29 |
U{XEP-0114<http://xmpp.org/extensions/xep-0114.html>}. |
| 30 |
""" |
| 31 |
|
| 32 |
def __init__(self, host, port, jid, password): |
| 33 |
self.host = host |
| 34 |
self.port = port |
| 35 |
|
| 36 |
factory = component.componentFactory(jid, password) |
| 37 |
|
| 38 |
StreamManager.__init__(self, factory) |
| 39 |
|
| 40 |
def _authd(self, xs): |
| 41 |
""" |
| 42 |
Called when stream initialization has completed. |
| 43 |
|
| 44 |
This replaces the C{send} method of the C{XmlStream} instance |
| 45 |
that represents the current connection so that outgoing stanzas |
| 46 |
always have a from attribute set to the JID of the component. |
| 47 |
""" |
| 48 |
old_send = xs.send |
| 49 |
|
| 50 |
def send(obj): |
| 51 |
if domish.IElement.providedBy(obj) and not obj.getAttribute("from"): |
| 52 |
obj["from"] = self.xmlstream.thisEntity.full() |
| 53 |
old_send(obj) |
| 54 |
|
| 55 |
xs.send = send |
| 56 |
StreamManager._authd(self, xs) |
| 57 |
|
| 58 |
def initializationFailed(self, reason): |
| 59 |
""" |
| 60 |
Called when stream initialization has failed. |
| 61 |
|
| 62 |
Stop the service (thereby disconnecting the current stream) and |
| 63 |
raise the exception. |
| 64 |
""" |
| 65 |
self.stopService() |
| 66 |
reason.raiseException() |
| 67 |
|
| 68 |
def startService(self): |
| 69 |
""" |
| 70 |
Start the service and connect to the server. |
| 71 |
""" |
| 72 |
service.Service.startService(self) |
| 73 |
|
| 74 |
self._connection = self._getConnection() |
| 75 |
|
| 76 |
def stopService(self): |
| 77 |
""" |
| 78 |
Stop the service, close the connection and prevent reconnects. |
| 79 |
""" |
| 80 |
service.Service.stopService(self) |
| 81 |
|
| 82 |
self.factory.stopTrying() |
| 83 |
self._connection.disconnect() |
| 84 |
|
| 85 |
def _getConnection(self): |
| 86 |
""" |
| 87 |
Create a connector that connects to the server. |
| 88 |
""" |
| 89 |
return reactor.connectTCP(self.host, self.port, self.factory) |
| 90 |
|
| 91 |
|
| 92 |
class InternalComponent(xmlstream.XMPPHandlerCollection, service.Service): |
| 93 |
""" |
| 94 |
Component service that connects directly to a router. |
| 95 |
|
| 96 |
Instead of opening a socket to connect to a router, like L{Component}, |
| 97 |
components of this type connect to a router in the same process. This |
| 98 |
allows for one-process XMPP servers. |
| 99 |
|
| 100 |
@ivar domains: Domains (as L{str}) this component will handle traffic |
| 101 |
for. |
| 102 |
@type domains: L{set} |
| 103 |
""" |
| 104 |
|
| 105 |
def __init__(self, router, domain=None): |
| 106 |
xmlstream.XMPPHandlerCollection.__init__(self) |
| 107 |
|
| 108 |
self._router = router |
| 109 |
self.domains = set() |
| 110 |
if domain: |
| 111 |
self.domains.add(domain) |
| 112 |
|
| 113 |
self.xmlstream = None |
| 114 |
|
| 115 |
def startService(self): |
| 116 |
""" |
| 117 |
Create a XML pipe, connect to the router and setup handlers. |
| 118 |
""" |
| 119 |
service.Service.startService(self) |
| 120 |
|
| 121 |
self._pipe = XmlPipe() |
| 122 |
self.xmlstream = self._pipe.source |
| 123 |
|
| 124 |
for domain in self.domains: |
| 125 |
self._router.addRoute(domain, self._pipe.sink) |
| 126 |
|
| 127 |
for e in self: |
| 128 |
e.makeConnection(self.xmlstream) |
| 129 |
e.connectionInitialized() |
| 130 |
|
| 131 |
def stopService(self): |
| 132 |
""" |
| 133 |
Disconnect from the router and handlers. |
| 134 |
""" |
| 135 |
service.Service.stopService(self) |
| 136 |
|
| 137 |
for domain in self.domains: |
| 138 |
self._router.removeRoute(domain, self._pipe.sink) |
| 139 |
|
| 140 |
self._pipe = None |
| 141 |
self.xmlstream = None |
| 142 |
|
| 143 |
for e in self: |
| 144 |
e.connectionLost(None) |
| 145 |
|
| 146 |
def addHandler(self, handler): |
| 147 |
""" |
| 148 |
Add a new handler and connect it to the stream. |
| 149 |
""" |
| 150 |
xmlstream.XMPPHandlerCollection.addHandler(self, handler) |
| 151 |
|
| 152 |
if self.xmlstream: |
| 153 |
handler.makeConnection(self.xmlstream) |
| 154 |
handler.connectionInitialized() |
| 155 |
|
| 156 |
def send(self, obj): |
| 157 |
""" |
| 158 |
Send data to the XML stream, so it ends up at the router. |
| 159 |
""" |
| 160 |
self.xmlstream.send(obj) |
| 161 |
|
| 162 |
|
| 163 |
class ListenComponentAuthenticator(xmlstream.ListenAuthenticator): |
| 164 |
""" |
| 165 |
Authenticator for accepting components. |
| 166 |
|
| 167 |
@ivar secret: The shared used to authorized incoming component connections. |
| 168 |
@type secret: L{str}. |
| 169 |
""" |
| 170 |
|
| 171 |
namespace = NS_COMPONENT_ACCEPT |
| 172 |
|
| 173 |
def __init__(self, secret): |
| 174 |
self.secret = secret |
| 175 |
xmlstream.ListenAuthenticator.__init__(self) |
| 176 |
|
| 177 |
def associateWithStream(self, xs): |
| 178 |
""" |
| 179 |
Associate the authenticator with a stream. |
| 180 |
|
| 181 |
This sets the stream's version to 0.0, because the XEP-0114 component |
| 182 |
protocol was not designed for XMPP 1.0. |
| 183 |
""" |
| 184 |
xs.version = (0, 0) |
| 185 |
xmlstream.ListenAuthenticator.associateWithStream(self, xs) |
| 186 |
|
| 187 |
def streamStarted(self, rootElement): |
| 188 |
""" |
| 189 |
Called by the stream when it has started. |
| 190 |
|
| 191 |
This examines the default namespace of the incoming stream and whether |
| 192 |
there is a requested hostname for the component. Then it generates a |
| 193 |
stream identifier, sends a response header and adds an observer for |
| 194 |
the first incoming element, triggering L{onElement}. |
| 195 |
""" |
| 196 |
|
| 197 |
xmlstream.ListenAuthenticator.streamStarted(self, rootElement) |
| 198 |
|
| 199 |
# Compatibility fix for pre-8.2 implementations of ListenAuthenticator |
| 200 |
if not self.xmlstream.sid: |
| 201 |
from twisted.python import randbytes |
| 202 |
|
| 203 |
self.xmlstream.sid = randbytes.secureRandom(8).encode("hex") |
| 204 |
|
| 205 |
if rootElement.defaultUri != self.namespace: |
| 206 |
exc = error.StreamError("invalid-namespace") |
| 207 |
self.xmlstream.sendStreamError(exc) |
| 208 |
return |
| 209 |
|
| 210 |
# self.xmlstream.thisEntity is set to the address the component |
| 211 |
# wants to assume. |
| 212 |
if not self.xmlstream.thisEntity: |
| 213 |
exc = error.StreamError("improper-addressing") |
| 214 |
self.xmlstream.sendStreamError(exc) |
| 215 |
return |
| 216 |
|
| 217 |
self.xmlstream.sendHeader() |
| 218 |
self.xmlstream.addOnetimeObserver("/*", self.onElement) |
| 219 |
|
| 220 |
def onElement(self, element): |
| 221 |
""" |
| 222 |
Called on incoming XML Stanzas. |
| 223 |
|
| 224 |
The very first element received should be a request for handshake. |
| 225 |
Otherwise, the stream is dropped with a 'not-authorized' error. If a |
| 226 |
handshake request was received, the hash is extracted and passed to |
| 227 |
L{onHandshake}. |
| 228 |
""" |
| 229 |
if (element.uri, element.name) == (self.namespace, "handshake"): |
| 230 |
self.onHandshake(str(element)) |
| 231 |
else: |
| 232 |
exc = error.StreamError("not-authorized") |
| 233 |
self.xmlstream.sendStreamError(exc) |
| 234 |
|
| 235 |
def onHandshake(self, handshake): |
| 236 |
""" |
| 237 |
Called upon receiving the handshake request. |
| 238 |
|
| 239 |
This checks that the given hash in C{handshake} is equal to a |
| 240 |
calculated hash, responding with a handshake reply or a stream error. |
| 241 |
If the handshake was ok, the stream is authorized, and XML Stanzas may |
| 242 |
be exchanged. |
| 243 |
""" |
| 244 |
calculatedHash = xmlstream.hashPassword(self.xmlstream.sid, str(self.secret)) |
| 245 |
if handshake != calculatedHash: |
| 246 |
exc = error.StreamError("not-authorized", text="Invalid hash") |
| 247 |
self.xmlstream.sendStreamError(exc) |
| 248 |
else: |
| 249 |
self.xmlstream.send("<handshake/>") |
| 250 |
self.xmlstream.dispatch(self.xmlstream, xmlstream.STREAM_AUTHD_EVENT) |
| 251 |
|
| 252 |
|
| 253 |
class Router: |
| 254 |
""" |
| 255 |
XMPP Server's Router. |
| 256 |
|
| 257 |
A router connects the different components of the XMPP service and routes |
| 258 |
messages between them based on the given routing table. |
| 259 |
|
| 260 |
Connected components are trusted to have correct addressing in the |
| 261 |
stanzas they offer for routing. |
| 262 |
|
| 263 |
A route destination of L{None} adds a default route. Traffic for which no |
| 264 |
specific route exists, will be routed to this default route. |
| 265 |
|
| 266 |
@ivar routes: Routes based on the host part of JIDs. Maps host names to the |
| 267 |
L{EventDispatcher<twisted.words.xish.utility.EventDispatcher>}s that |
| 268 |
should receive the traffic. A key of L{None} means the default route. |
| 269 |
@type routes: L{dict} |
| 270 |
""" |
| 271 |
|
| 272 |
def __init__(self): |
| 273 |
self.routes = {} |
| 274 |
|
| 275 |
def addRoute(self, destination, xs): |
| 276 |
""" |
| 277 |
Add a new route. |
| 278 |
|
| 279 |
The passed XML Stream C{xs} will have an observer for all stanzas |
| 280 |
added to route its outgoing traffic. In turn, traffic for |
| 281 |
C{destination} will be passed to this stream. |
| 282 |
|
| 283 |
@param destination: Destination of the route to be added as a host name |
| 284 |
or L{None} for the default route. |
| 285 |
@type destination: L{str} or L{NoneType} |
| 286 |
|
| 287 |
@param xs: XML Stream to register the route for. |
| 288 |
@type xs: |
| 289 |
L{EventDispatcher<twisted.words.xish.utility.EventDispatcher>} |
| 290 |
""" |
| 291 |
self.routes[destination] = xs |
| 292 |
xs.addObserver("/*", self.route) |
| 293 |
|
| 294 |
def removeRoute(self, destination, xs): |
| 295 |
""" |
| 296 |
Remove a route. |
| 297 |
|
| 298 |
@param destination: Destination of the route that should be removed. |
| 299 |
@type destination: L{str} |
| 300 |
|
| 301 |
@param xs: XML Stream to remove the route for. |
| 302 |
@type xs: |
| 303 |
L{EventDispatcher<twisted.words.xish.utility.EventDispatcher>} |
| 304 |
""" |
| 305 |
xs.removeObserver("/*", self.route) |
| 306 |
if xs == self.routes[destination]: |
| 307 |
del self.routes[destination] |
| 308 |
|
| 309 |
def route(self, stanza): |
| 310 |
""" |
| 311 |
Route a stanza. |
| 312 |
|
| 313 |
@param stanza: The stanza to be routed. |
| 314 |
@type stanza: L{domish.Element}. |
| 315 |
""" |
| 316 |
destination = JID(stanza["to"]) |
| 317 |
|
| 318 |
if destination.host in self.routes: |
| 319 |
log.msg("Routing to %s: %r" % (destination.full(), stanza.toXml())) |
| 320 |
self.routes[destination.host].send(stanza) |
| 321 |
elif None in self.routes: |
| 322 |
log.msg( |
| 323 |
"Routing to %s (default route): %r" % (destination.full(), stanza.toXml()) |
| 324 |
) |
| 325 |
self.routes[None].send(stanza) |
| 326 |
else: |
| 327 |
log.msg("No route to %s: %r" % (destination.full(), stanza.toXml())) |
| 328 |
if stanza.getAttribute("type") not in ("result", "error"): |
| 329 |
# No route, send back error |
| 330 |
exc = error.StanzaError("remote-server-timeout", type="wait") |
| 331 |
exc.code = "504" |
| 332 |
response = exc.toResponse(stanza) |
| 333 |
self.route(response) |
| 334 |
|
| 335 |
|
| 336 |
class XMPPComponentServerFactory(xmlstream.XmlStreamServerFactory): |
| 337 |
""" |
| 338 |
XMPP Component Server factory. |
| 339 |
|
| 340 |
This factory accepts XMPP external component connections and makes |
| 341 |
the router service route traffic for a component's bound domain |
| 342 |
to that component. |
| 343 |
""" |
| 344 |
|
| 345 |
logTraffic = False |
| 346 |
|
| 347 |
def __init__(self, router, secret="secret"): |
| 348 |
self.router = router |
| 349 |
self.secret = secret |
| 350 |
|
| 351 |
def authenticatorFactory(): |
| 352 |
return ListenComponentAuthenticator(self.secret) |
| 353 |
|
| 354 |
xmlstream.XmlStreamServerFactory.__init__(self, authenticatorFactory) |
| 355 |
self.addBootstrap(xmlstream.STREAM_CONNECTED_EVENT, self.makeConnection) |
| 356 |
self.addBootstrap(xmlstream.STREAM_AUTHD_EVENT, self.connectionInitialized) |
| 357 |
|
| 358 |
self.serial = 0 |
| 359 |
|
| 360 |
def makeConnection(self, xs): |
| 361 |
""" |
| 362 |
Called when a component connection was made. |
| 363 |
|
| 364 |
This enables traffic debugging on incoming streams. |
| 365 |
""" |
| 366 |
xs.serial = self.serial |
| 367 |
self.serial += 1 |
| 368 |
|
| 369 |
def logDataIn(buf): |
| 370 |
log.msg("RECV (%d): %r" % (xs.serial, buf)) |
| 371 |
|
| 372 |
def logDataOut(buf): |
| 373 |
log.msg("SEND (%d): %r" % (xs.serial, buf)) |
| 374 |
|
| 375 |
if self.logTraffic: |
| 376 |
xs.rawDataInFn = logDataIn |
| 377 |
xs.rawDataOutFn = logDataOut |
| 378 |
|
| 379 |
xs.addObserver(xmlstream.STREAM_ERROR_EVENT, self.onError) |
| 380 |
|
| 381 |
def connectionInitialized(self, xs): |
| 382 |
""" |
| 383 |
Called when a component has succesfully authenticated. |
| 384 |
|
| 385 |
Add the component to the routing table and establish a handler |
| 386 |
for a closed connection. |
| 387 |
""" |
| 388 |
destination = xs.thisEntity.host |
| 389 |
|
| 390 |
self.router.addRoute(destination, xs) |
| 391 |
xs.addObserver( |
| 392 |
xmlstream.STREAM_END_EVENT, self.connectionLost, 0, destination, xs |
| 393 |
) |
| 394 |
|
| 395 |
def onError(self, reason): |
| 396 |
log.err(reason, "Stream Error") |
| 397 |
|
| 398 |
def connectionLost(self, destination, xs, reason): |
| 399 |
self.router.removeRoute(destination, xs) |