component.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. # -*- test-case-name: twisted.words.test.test_jabbercomponent -*-
  2. #
  3. # Copyright (c) Twisted Matrix Laboratories.
  4. # See LICENSE for details.
  5. """
  6. External server-side components.
  7. Most Jabber server implementations allow for add-on components that act as a
  8. separate entity on the Jabber network, but use the server-to-server
  9. functionality of a regular Jabber IM server. These so-called 'external
  10. components' are connected to the Jabber server using the Jabber Component
  11. Protocol as defined in U{JEP-0114<http://www.jabber.org/jeps/jep-0114.html>}.
  12. This module allows for writing external server-side component by assigning one
  13. or more services implementing L{ijabber.IService} up to L{ServiceManager}. The
  14. ServiceManager connects to the Jabber server and is responsible for the
  15. corresponding XML stream.
  16. """
  17. from zope.interface import implementer
  18. from twisted.application import service
  19. from twisted.internet import defer
  20. from twisted.python import log
  21. from twisted.words.protocols.jabber import error, ijabber, jstrports, xmlstream
  22. from twisted.words.protocols.jabber.jid import internJID as JID
  23. from twisted.words.xish import domish
  24. NS_COMPONENT_ACCEPT = "jabber:component:accept"
  25. def componentFactory(componentid, password):
  26. """
  27. XML stream factory for external server-side components.
  28. @param componentid: JID of the component.
  29. @type componentid: L{unicode}
  30. @param password: password used to authenticate to the server.
  31. @type password: C{str}
  32. """
  33. a = ConnectComponentAuthenticator(componentid, password)
  34. return xmlstream.XmlStreamFactory(a)
  35. class ComponentInitiatingInitializer:
  36. """
  37. External server-side component authentication initializer for the
  38. initiating entity.
  39. @ivar xmlstream: XML stream between server and component.
  40. @type xmlstream: L{xmlstream.XmlStream}
  41. """
  42. def __init__(self, xs):
  43. self.xmlstream = xs
  44. self._deferred = None
  45. def initialize(self):
  46. xs = self.xmlstream
  47. hs = domish.Element((self.xmlstream.namespace, "handshake"))
  48. digest = xmlstream.hashPassword(xs.sid, xs.authenticator.password)
  49. hs.addContent(str(digest))
  50. # Setup observer to watch for handshake result
  51. xs.addOnetimeObserver("/handshake", self._cbHandshake)
  52. xs.send(hs)
  53. self._deferred = defer.Deferred()
  54. return self._deferred
  55. def _cbHandshake(self, _):
  56. # we have successfully shaken hands and can now consider this
  57. # entity to represent the component JID.
  58. self.xmlstream.thisEntity = self.xmlstream.otherEntity
  59. self._deferred.callback(None)
  60. class ConnectComponentAuthenticator(xmlstream.ConnectAuthenticator):
  61. """
  62. Authenticator to permit an XmlStream to authenticate against a Jabber
  63. server as an external component (where the Authenticator is initiating the
  64. stream).
  65. """
  66. namespace = NS_COMPONENT_ACCEPT
  67. def __init__(self, componentjid, password):
  68. """
  69. @type componentjid: C{str}
  70. @param componentjid: Jabber ID that this component wishes to bind to.
  71. @type password: C{str}
  72. @param password: Password/secret this component uses to authenticate.
  73. """
  74. # Note that we are sending 'to' our desired component JID.
  75. xmlstream.ConnectAuthenticator.__init__(self, componentjid)
  76. self.password = password
  77. def associateWithStream(self, xs):
  78. xs.version = (0, 0)
  79. xmlstream.ConnectAuthenticator.associateWithStream(self, xs)
  80. xs.initializers = [ComponentInitiatingInitializer(xs)]
  81. class ListenComponentAuthenticator(xmlstream.ListenAuthenticator):
  82. """
  83. Authenticator for accepting components.
  84. @since: 8.2
  85. @ivar secret: The shared secret used to authorized incoming component
  86. connections.
  87. @type secret: C{unicode}.
  88. """
  89. namespace = NS_COMPONENT_ACCEPT
  90. def __init__(self, secret):
  91. self.secret = secret
  92. xmlstream.ListenAuthenticator.__init__(self)
  93. def associateWithStream(self, xs):
  94. """
  95. Associate the authenticator with a stream.
  96. This sets the stream's version to 0.0, because the XEP-0114 component
  97. protocol was not designed for XMPP 1.0.
  98. """
  99. xs.version = (0, 0)
  100. xmlstream.ListenAuthenticator.associateWithStream(self, xs)
  101. def streamStarted(self, rootElement):
  102. """
  103. Called by the stream when it has started.
  104. This examines the default namespace of the incoming stream and whether
  105. there is a requested hostname for the component. Then it generates a
  106. stream identifier, sends a response header and adds an observer for
  107. the first incoming element, triggering L{onElement}.
  108. """
  109. xmlstream.ListenAuthenticator.streamStarted(self, rootElement)
  110. if rootElement.defaultUri != self.namespace:
  111. exc = error.StreamError("invalid-namespace")
  112. self.xmlstream.sendStreamError(exc)
  113. return
  114. # self.xmlstream.thisEntity is set to the address the component
  115. # wants to assume.
  116. if not self.xmlstream.thisEntity:
  117. exc = error.StreamError("improper-addressing")
  118. self.xmlstream.sendStreamError(exc)
  119. return
  120. self.xmlstream.sendHeader()
  121. self.xmlstream.addOnetimeObserver("/*", self.onElement)
  122. def onElement(self, element):
  123. """
  124. Called on incoming XML Stanzas.
  125. The very first element received should be a request for handshake.
  126. Otherwise, the stream is dropped with a 'not-authorized' error. If a
  127. handshake request was received, the hash is extracted and passed to
  128. L{onHandshake}.
  129. """
  130. if (element.uri, element.name) == (self.namespace, "handshake"):
  131. self.onHandshake(str(element))
  132. else:
  133. exc = error.StreamError("not-authorized")
  134. self.xmlstream.sendStreamError(exc)
  135. def onHandshake(self, handshake):
  136. """
  137. Called upon receiving the handshake request.
  138. This checks that the given hash in C{handshake} is equal to a
  139. calculated hash, responding with a handshake reply or a stream error.
  140. If the handshake was ok, the stream is authorized, and XML Stanzas may
  141. be exchanged.
  142. """
  143. calculatedHash = xmlstream.hashPassword(self.xmlstream.sid, str(self.secret))
  144. if handshake != calculatedHash:
  145. exc = error.StreamError("not-authorized", text="Invalid hash")
  146. self.xmlstream.sendStreamError(exc)
  147. else:
  148. self.xmlstream.send("<handshake/>")
  149. self.xmlstream.dispatch(self.xmlstream, xmlstream.STREAM_AUTHD_EVENT)
  150. @implementer(ijabber.IService)
  151. class Service(service.Service):
  152. """
  153. External server-side component service.
  154. """
  155. def componentConnected(self, xs):
  156. pass
  157. def componentDisconnected(self):
  158. pass
  159. def transportConnected(self, xs):
  160. pass
  161. def send(self, obj):
  162. """
  163. Send data over service parent's XML stream.
  164. @note: L{ServiceManager} maintains a queue for data sent using this
  165. method when there is no current established XML stream. This data is
  166. then sent as soon as a new stream has been established and initialized.
  167. Subsequently, L{componentConnected} will be called again. If this
  168. queueing is not desired, use C{send} on the XmlStream object (passed to
  169. L{componentConnected}) directly.
  170. @param obj: data to be sent over the XML stream. This is usually an
  171. object providing L{domish.IElement}, or serialized XML. See
  172. L{xmlstream.XmlStream} for details.
  173. """
  174. self.parent.send(obj)
  175. class ServiceManager(service.MultiService):
  176. """
  177. Business logic for a managed component connection to a Jabber router.
  178. This service maintains a single connection to a Jabber router and provides
  179. facilities for packet routing and transmission. Business logic modules are
  180. services implementing L{ijabber.IService} (like subclasses of L{Service}),
  181. and added as sub-service.
  182. """
  183. def __init__(self, jid, password):
  184. service.MultiService.__init__(self)
  185. # Setup defaults
  186. self.jabberId = jid
  187. self.xmlstream = None
  188. # Internal buffer of packets
  189. self._packetQueue = []
  190. # Setup the xmlstream factory
  191. self._xsFactory = componentFactory(self.jabberId, password)
  192. # Register some lambda functions to keep the self.xmlstream var up to
  193. # date
  194. self._xsFactory.addBootstrap(xmlstream.STREAM_CONNECTED_EVENT, self._connected)
  195. self._xsFactory.addBootstrap(xmlstream.STREAM_AUTHD_EVENT, self._authd)
  196. self._xsFactory.addBootstrap(xmlstream.STREAM_END_EVENT, self._disconnected)
  197. # Map addBootstrap and removeBootstrap to the underlying factory -- is
  198. # this right? I have no clue...but it'll work for now, until i can
  199. # think about it more.
  200. self.addBootstrap = self._xsFactory.addBootstrap
  201. self.removeBootstrap = self._xsFactory.removeBootstrap
  202. def getFactory(self):
  203. return self._xsFactory
  204. def _connected(self, xs):
  205. self.xmlstream = xs
  206. for c in self:
  207. if ijabber.IService.providedBy(c):
  208. c.transportConnected(xs)
  209. def _authd(self, xs):
  210. # Flush all pending packets
  211. for p in self._packetQueue:
  212. self.xmlstream.send(p)
  213. self._packetQueue = []
  214. # Notify all child services which implement the IService interface
  215. for c in self:
  216. if ijabber.IService.providedBy(c):
  217. c.componentConnected(xs)
  218. def _disconnected(self, _):
  219. self.xmlstream = None
  220. # Notify all child services which implement
  221. # the IService interface
  222. for c in self:
  223. if ijabber.IService.providedBy(c):
  224. c.componentDisconnected()
  225. def send(self, obj):
  226. """
  227. Send data over the XML stream.
  228. When there is no established XML stream, the data is queued and sent
  229. out when a new XML stream has been established and initialized.
  230. @param obj: data to be sent over the XML stream. This is usually an
  231. object providing L{domish.IElement}, or serialized XML. See
  232. L{xmlstream.XmlStream} for details.
  233. """
  234. if self.xmlstream != None:
  235. self.xmlstream.send(obj)
  236. else:
  237. self._packetQueue.append(obj)
  238. def buildServiceManager(jid, password, strport):
  239. """
  240. Constructs a pre-built L{ServiceManager}, using the specified strport
  241. string.
  242. """
  243. svc = ServiceManager(jid, password)
  244. client_svc = jstrports.client(strport, svc.getFactory())
  245. client_svc.setServiceParent(svc)
  246. return svc
  247. class Router:
  248. """
  249. XMPP Server's Router.
  250. A router connects the different components of the XMPP service and routes
  251. messages between them based on the given routing table.
  252. Connected components are trusted to have correct addressing in the
  253. stanzas they offer for routing.
  254. A route destination of L{None} adds a default route. Traffic for which no
  255. specific route exists, will be routed to this default route.
  256. @since: 8.2
  257. @ivar routes: Routes based on the host part of JIDs. Maps host names to the
  258. L{EventDispatcher<utility.EventDispatcher>}s that should
  259. receive the traffic. A key of L{None} means the default
  260. route.
  261. @type routes: C{dict}
  262. """
  263. def __init__(self):
  264. self.routes = {}
  265. def addRoute(self, destination, xs):
  266. """
  267. Add a new route.
  268. The passed XML Stream C{xs} will have an observer for all stanzas
  269. added to route its outgoing traffic. In turn, traffic for
  270. C{destination} will be passed to this stream.
  271. @param destination: Destination of the route to be added as a host name
  272. or L{None} for the default route.
  273. @type destination: C{str} or L{None}.
  274. @param xs: XML Stream to register the route for.
  275. @type xs: L{EventDispatcher<utility.EventDispatcher>}.
  276. """
  277. self.routes[destination] = xs
  278. xs.addObserver("/*", self.route)
  279. def removeRoute(self, destination, xs):
  280. """
  281. Remove a route.
  282. @param destination: Destination of the route that should be removed.
  283. @type destination: C{str}.
  284. @param xs: XML Stream to remove the route for.
  285. @type xs: L{EventDispatcher<utility.EventDispatcher>}.
  286. """
  287. xs.removeObserver("/*", self.route)
  288. if xs == self.routes[destination]:
  289. del self.routes[destination]
  290. def route(self, stanza):
  291. """
  292. Route a stanza.
  293. @param stanza: The stanza to be routed.
  294. @type stanza: L{domish.Element}.
  295. """
  296. destination = JID(stanza["to"])
  297. log.msg(f"Routing to {destination.full()}: {stanza.toXml()!r}")
  298. if destination.host in self.routes:
  299. self.routes[destination.host].send(stanza)
  300. else:
  301. self.routes[None].send(stanza)
  302. class XMPPComponentServerFactory(xmlstream.XmlStreamServerFactory):
  303. """
  304. XMPP Component Server factory.
  305. This factory accepts XMPP external component connections and makes
  306. the router service route traffic for a component's bound domain
  307. to that component.
  308. @since: 8.2
  309. """
  310. logTraffic = False
  311. def __init__(self, router, secret="secret"):
  312. self.router = router
  313. self.secret = secret
  314. def authenticatorFactory():
  315. return ListenComponentAuthenticator(self.secret)
  316. xmlstream.XmlStreamServerFactory.__init__(self, authenticatorFactory)
  317. self.addBootstrap(xmlstream.STREAM_CONNECTED_EVENT, self.onConnectionMade)
  318. self.addBootstrap(xmlstream.STREAM_AUTHD_EVENT, self.onAuthenticated)
  319. self.serial = 0
  320. def onConnectionMade(self, xs):
  321. """
  322. Called when a component connection was made.
  323. This enables traffic debugging on incoming streams.
  324. """
  325. xs.serial = self.serial
  326. self.serial += 1
  327. def logDataIn(buf):
  328. log.msg("RECV (%d): %r" % (xs.serial, buf))
  329. def logDataOut(buf):
  330. log.msg("SEND (%d): %r" % (xs.serial, buf))
  331. if self.logTraffic:
  332. xs.rawDataInFn = logDataIn
  333. xs.rawDataOutFn = logDataOut
  334. xs.addObserver(xmlstream.STREAM_ERROR_EVENT, self.onError)
  335. def onAuthenticated(self, xs):
  336. """
  337. Called when a component has successfully authenticated.
  338. Add the component to the routing table and establish a handler
  339. for a closed connection.
  340. """
  341. destination = xs.thisEntity.host
  342. self.router.addRoute(destination, xs)
  343. xs.addObserver(
  344. xmlstream.STREAM_END_EVENT, self.onConnectionLost, 0, destination, xs
  345. )
  346. def onError(self, reason):
  347. log.err(reason, "Stream Error")
  348. def onConnectionLost(self, destination, xs, reason):
  349. self.router.removeRoute(destination, xs)