component.py 15 KB

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