xmlstream.py 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  1. # -*- test-case-name: twisted.words.test.test_jabberxmlstream -*-
  2. #
  3. # Copyright (c) Twisted Matrix Laboratories.
  4. # See LICENSE for details.
  5. """
  6. XMPP XML Streams
  7. Building blocks for setting up XML Streams, including helping classes for
  8. doing authentication on either client or server side, and working with XML
  9. Stanzas.
  10. @var STREAM_AUTHD_EVENT: Token dispatched by L{Authenticator} when the
  11. stream has been completely initialized
  12. @type STREAM_AUTHD_EVENT: L{str}.
  13. @var INIT_FAILED_EVENT: Token dispatched by L{Authenticator} when the
  14. stream has failed to be initialized
  15. @type INIT_FAILED_EVENT: L{str}.
  16. @var Reset: Token to signal that the XML stream has been reset.
  17. @type Reset: Basic object.
  18. """
  19. from binascii import hexlify
  20. from hashlib import sha1
  21. from sys import intern
  22. from typing import Optional, Tuple
  23. from zope.interface import directlyProvides, implementer
  24. from twisted.internet import defer, protocol
  25. from twisted.internet.error import ConnectionLost
  26. from twisted.python import failure, log, randbytes
  27. from twisted.words.protocols.jabber import error, ijabber, jid
  28. from twisted.words.xish import domish, xmlstream
  29. from twisted.words.xish.xmlstream import (
  30. STREAM_CONNECTED_EVENT,
  31. STREAM_END_EVENT,
  32. STREAM_ERROR_EVENT,
  33. STREAM_START_EVENT,
  34. )
  35. try:
  36. from twisted.internet import ssl as _ssl
  37. except ImportError:
  38. ssl = None
  39. else:
  40. if not _ssl.supported:
  41. ssl = None
  42. else:
  43. ssl = _ssl
  44. STREAM_AUTHD_EVENT = intern("//event/stream/authd")
  45. INIT_FAILED_EVENT = intern("//event/xmpp/initfailed")
  46. NS_STREAMS = "http://etherx.jabber.org/streams"
  47. NS_XMPP_TLS = "urn:ietf:params:xml:ns:xmpp-tls"
  48. Reset = object()
  49. def hashPassword(sid, password):
  50. """
  51. Create a SHA1-digest string of a session identifier and password.
  52. @param sid: The stream session identifier.
  53. @type sid: C{unicode}.
  54. @param password: The password to be hashed.
  55. @type password: C{unicode}.
  56. """
  57. if not isinstance(sid, str):
  58. raise TypeError("The session identifier must be a unicode object")
  59. if not isinstance(password, str):
  60. raise TypeError("The password must be a unicode object")
  61. input = f"{sid}{password}"
  62. return sha1(input.encode("utf-8")).hexdigest()
  63. class Authenticator:
  64. """
  65. Base class for business logic of initializing an XmlStream
  66. Subclass this object to enable an XmlStream to initialize and authenticate
  67. to different types of stream hosts (such as clients, components, etc.).
  68. Rules:
  69. 1. The Authenticator MUST dispatch a L{STREAM_AUTHD_EVENT} when the
  70. stream has been completely initialized.
  71. 2. The Authenticator SHOULD reset all state information when
  72. L{associateWithStream} is called.
  73. 3. The Authenticator SHOULD override L{streamStarted}, and start
  74. initialization there.
  75. @type xmlstream: L{XmlStream}
  76. @ivar xmlstream: The XmlStream that needs authentication
  77. @note: the term authenticator is historical. Authenticators perform
  78. all steps required to prepare the stream for the exchange
  79. of XML stanzas.
  80. """
  81. def __init__(self):
  82. self.xmlstream = None
  83. def connectionMade(self):
  84. """
  85. Called by the XmlStream when the underlying socket connection is
  86. in place.
  87. This allows the Authenticator to send an initial root element, if it's
  88. connecting, or wait for an inbound root from the peer if it's accepting
  89. the connection.
  90. Subclasses can use self.xmlstream.send() to send any initial data to
  91. the peer.
  92. """
  93. def streamStarted(self, rootElement):
  94. """
  95. Called by the XmlStream when the stream has started.
  96. A stream is considered to have started when the start tag of the root
  97. element has been received.
  98. This examines C{rootElement} to see if there is a version attribute.
  99. If absent, C{0.0} is assumed per RFC 3920. Subsequently, the
  100. minimum of the version from the received stream header and the
  101. value stored in L{xmlstream} is taken and put back in L{xmlstream}.
  102. Extensions of this method can extract more information from the
  103. stream header and perform checks on them, optionally sending
  104. stream errors and closing the stream.
  105. """
  106. if rootElement.hasAttribute("version"):
  107. version = rootElement["version"].split(".")
  108. try:
  109. version = (int(version[0]), int(version[1]))
  110. except (IndexError, ValueError):
  111. version = (0, 0)
  112. else:
  113. version = (0, 0)
  114. self.xmlstream.version = min(self.xmlstream.version, version)
  115. def associateWithStream(self, xmlstream):
  116. """
  117. Called by the XmlStreamFactory when a connection has been made
  118. to the requested peer, and an XmlStream object has been
  119. instantiated.
  120. The default implementation just saves a handle to the new
  121. XmlStream.
  122. @type xmlstream: L{XmlStream}
  123. @param xmlstream: The XmlStream that will be passing events to this
  124. Authenticator.
  125. """
  126. self.xmlstream = xmlstream
  127. class ConnectAuthenticator(Authenticator):
  128. """
  129. Authenticator for initiating entities.
  130. """
  131. namespace: Optional[str] = None
  132. def __init__(self, otherHost):
  133. self.otherHost = otherHost
  134. def connectionMade(self):
  135. self.xmlstream.namespace = self.namespace
  136. self.xmlstream.otherEntity = jid.internJID(self.otherHost)
  137. self.xmlstream.sendHeader()
  138. def initializeStream(self):
  139. """
  140. Perform stream initialization procedures.
  141. An L{XmlStream} holds a list of initializer objects in its
  142. C{initializers} attribute. This method calls these initializers in
  143. order and dispatches the L{STREAM_AUTHD_EVENT} event when the list has
  144. been successfully processed. Otherwise it dispatches the
  145. C{INIT_FAILED_EVENT} event with the failure.
  146. Initializers may return the special L{Reset} object to halt the
  147. initialization processing. It signals that the current initializer was
  148. successfully processed, but that the XML Stream has been reset. An
  149. example is the TLSInitiatingInitializer.
  150. """
  151. def remove_first(result):
  152. self.xmlstream.initializers.pop(0)
  153. return result
  154. def do_next(result):
  155. """
  156. Take the first initializer and process it.
  157. On success, the initializer is removed from the list and
  158. then next initializer will be tried.
  159. """
  160. if result is Reset:
  161. return None
  162. try:
  163. init = self.xmlstream.initializers[0]
  164. except IndexError:
  165. self.xmlstream.dispatch(self.xmlstream, STREAM_AUTHD_EVENT)
  166. return None
  167. else:
  168. d = defer.maybeDeferred(init.initialize)
  169. d.addCallback(remove_first)
  170. d.addCallback(do_next)
  171. return d
  172. d = defer.succeed(None)
  173. d.addCallback(do_next)
  174. d.addErrback(self.xmlstream.dispatch, INIT_FAILED_EVENT)
  175. def streamStarted(self, rootElement):
  176. """
  177. Called by the XmlStream when the stream has started.
  178. This extends L{Authenticator.streamStarted} to extract further stream
  179. headers from C{rootElement}, optionally wait for stream features being
  180. received and then call C{initializeStream}.
  181. """
  182. Authenticator.streamStarted(self, rootElement)
  183. self.xmlstream.sid = rootElement.getAttribute("id")
  184. if rootElement.hasAttribute("from"):
  185. self.xmlstream.otherEntity = jid.internJID(rootElement["from"])
  186. # Setup observer for stream features, if applicable
  187. if self.xmlstream.version >= (1, 0):
  188. def onFeatures(element):
  189. features = {}
  190. for feature in element.elements():
  191. features[(feature.uri, feature.name)] = feature
  192. self.xmlstream.features = features
  193. self.initializeStream()
  194. self.xmlstream.addOnetimeObserver(
  195. '/features[@xmlns="%s"]' % NS_STREAMS, onFeatures
  196. )
  197. else:
  198. self.initializeStream()
  199. class ListenAuthenticator(Authenticator):
  200. """
  201. Authenticator for receiving entities.
  202. """
  203. namespace: Optional[str] = None
  204. def associateWithStream(self, xmlstream):
  205. """
  206. Called by the XmlStreamFactory when a connection has been made.
  207. Extend L{Authenticator.associateWithStream} to set the L{XmlStream}
  208. to be non-initiating.
  209. """
  210. Authenticator.associateWithStream(self, xmlstream)
  211. self.xmlstream.initiating = False
  212. def streamStarted(self, rootElement):
  213. """
  214. Called by the XmlStream when the stream has started.
  215. This extends L{Authenticator.streamStarted} to extract further
  216. information from the stream headers from C{rootElement}.
  217. """
  218. Authenticator.streamStarted(self, rootElement)
  219. self.xmlstream.namespace = rootElement.defaultUri
  220. if rootElement.hasAttribute("to"):
  221. self.xmlstream.thisEntity = jid.internJID(rootElement["to"])
  222. self.xmlstream.prefixes = {}
  223. for prefix, uri in rootElement.localPrefixes.items():
  224. self.xmlstream.prefixes[uri] = prefix
  225. self.xmlstream.sid = hexlify(randbytes.secureRandom(8)).decode("ascii")
  226. class FeatureNotAdvertized(Exception):
  227. """
  228. Exception indicating a stream feature was not advertized, while required by
  229. the initiating entity.
  230. """
  231. @implementer(ijabber.IInitiatingInitializer)
  232. class BaseFeatureInitiatingInitializer:
  233. """
  234. Base class for initializers with a stream feature.
  235. This assumes the associated XmlStream represents the initiating entity
  236. of the connection.
  237. @cvar feature: tuple of (uri, name) of the stream feature root element.
  238. @type feature: tuple of (C{str}, C{str})
  239. @ivar required: whether the stream feature is required to be advertized
  240. by the receiving entity.
  241. @type required: C{bool}
  242. """
  243. feature: Optional[Tuple[str, str]] = None
  244. def __init__(self, xs, required=False):
  245. self.xmlstream = xs
  246. self.required = required
  247. def initialize(self):
  248. """
  249. Initiate the initialization.
  250. Checks if the receiving entity advertizes the stream feature. If it
  251. does, the initialization is started. If it is not advertized, and the
  252. C{required} instance variable is C{True}, it raises
  253. L{FeatureNotAdvertized}. Otherwise, the initialization silently
  254. succeeds.
  255. """
  256. if self.feature in self.xmlstream.features:
  257. return self.start()
  258. elif self.required:
  259. raise FeatureNotAdvertized
  260. else:
  261. return None
  262. def start(self):
  263. """
  264. Start the actual initialization.
  265. May return a deferred for asynchronous initialization.
  266. """
  267. class TLSError(Exception):
  268. """
  269. TLS base exception.
  270. """
  271. class TLSFailed(TLSError):
  272. """
  273. Exception indicating failed TLS negotiation
  274. """
  275. class TLSRequired(TLSError):
  276. """
  277. Exception indicating required TLS negotiation.
  278. This exception is raised when the receiving entity requires TLS
  279. negotiation and the initiating does not desire to negotiate TLS.
  280. """
  281. class TLSNotSupported(TLSError):
  282. """
  283. Exception indicating missing TLS support.
  284. This exception is raised when the initiating entity wants and requires to
  285. negotiate TLS when the OpenSSL library is not available.
  286. """
  287. class TLSInitiatingInitializer(BaseFeatureInitiatingInitializer):
  288. """
  289. TLS stream initializer for the initiating entity.
  290. It is strongly required to include this initializer in the list of
  291. initializers for an XMPP stream. By default it will try to negotiate TLS.
  292. An XMPP server may indicate that TLS is required. If TLS is not desired,
  293. set the C{wanted} attribute to False instead of removing it from the list
  294. of initializers, so a proper exception L{TLSRequired} can be raised.
  295. @ivar wanted: indicates if TLS negotiation is wanted.
  296. @type wanted: C{bool}
  297. """
  298. feature = (NS_XMPP_TLS, "starttls")
  299. wanted = True
  300. _deferred = None
  301. _configurationForTLS = None
  302. def __init__(self, xs, required=True, configurationForTLS=None):
  303. """
  304. @param configurationForTLS: An object which creates appropriately
  305. configured TLS connections. This is passed to C{startTLS} on the
  306. transport and is preferably created using
  307. L{twisted.internet.ssl.optionsForClientTLS}. If C{None}, the
  308. default is to verify the server certificate against the trust roots
  309. as provided by the platform. See
  310. L{twisted.internet._sslverify.platformTrust}.
  311. @type configurationForTLS: L{IOpenSSLClientConnectionCreator} or
  312. C{None}
  313. """
  314. super().__init__(xs, required=required)
  315. self._configurationForTLS = configurationForTLS
  316. def onProceed(self, obj):
  317. """
  318. Proceed with TLS negotiation and reset the XML stream.
  319. """
  320. self.xmlstream.removeObserver("/failure", self.onFailure)
  321. if self._configurationForTLS:
  322. ctx = self._configurationForTLS
  323. else:
  324. ctx = ssl.optionsForClientTLS(self.xmlstream.otherEntity.host)
  325. self.xmlstream.transport.startTLS(ctx)
  326. self.xmlstream.reset()
  327. self.xmlstream.sendHeader()
  328. self._deferred.callback(Reset)
  329. def onFailure(self, obj):
  330. self.xmlstream.removeObserver("/proceed", self.onProceed)
  331. self._deferred.errback(TLSFailed())
  332. def start(self):
  333. """
  334. Start TLS negotiation.
  335. This checks if the receiving entity requires TLS, the SSL library is
  336. available and uses the C{required} and C{wanted} instance variables to
  337. determine what to do in the various different cases.
  338. For example, if the SSL library is not available, and wanted and
  339. required by the user, it raises an exception. However if it is not
  340. required by both parties, initialization silently succeeds, moving
  341. on to the next step.
  342. """
  343. if self.wanted:
  344. if ssl is None:
  345. if self.required:
  346. return defer.fail(TLSNotSupported())
  347. else:
  348. return defer.succeed(None)
  349. else:
  350. pass
  351. elif self.xmlstream.features[self.feature].required:
  352. return defer.fail(TLSRequired())
  353. else:
  354. return defer.succeed(None)
  355. self._deferred = defer.Deferred()
  356. self.xmlstream.addOnetimeObserver("/proceed", self.onProceed)
  357. self.xmlstream.addOnetimeObserver("/failure", self.onFailure)
  358. self.xmlstream.send(domish.Element((NS_XMPP_TLS, "starttls")))
  359. return self._deferred
  360. class XmlStream(xmlstream.XmlStream):
  361. """
  362. XMPP XML Stream protocol handler.
  363. @ivar version: XML stream version as a tuple (major, minor). Initially,
  364. this is set to the minimally supported version. Upon
  365. receiving the stream header of the peer, it is set to the
  366. minimum of that value and the version on the received
  367. header.
  368. @type version: (C{int}, C{int})
  369. @ivar namespace: default namespace URI for stream
  370. @type namespace: C{unicode}
  371. @ivar thisEntity: JID of this entity
  372. @type thisEntity: L{JID}
  373. @ivar otherEntity: JID of the peer entity
  374. @type otherEntity: L{JID}
  375. @ivar sid: session identifier
  376. @type sid: C{unicode}
  377. @ivar initiating: True if this is the initiating stream
  378. @type initiating: C{bool}
  379. @ivar features: map of (uri, name) to stream features element received from
  380. the receiving entity.
  381. @type features: C{dict} of (C{unicode}, C{unicode}) to L{domish.Element}.
  382. @ivar prefixes: map of URI to prefixes that are to appear on stream
  383. header.
  384. @type prefixes: C{dict} of C{unicode} to C{unicode}
  385. @ivar initializers: list of stream initializer objects
  386. @type initializers: C{list} of objects that provide L{IInitializer}
  387. @ivar authenticator: associated authenticator that uses C{initializers} to
  388. initialize the XML stream.
  389. """
  390. version = (1, 0)
  391. namespace = "invalid"
  392. thisEntity = None
  393. otherEntity = None
  394. sid = None
  395. initiating = True
  396. _headerSent = False # True if the stream header has been sent
  397. def __init__(self, authenticator):
  398. xmlstream.XmlStream.__init__(self)
  399. self.prefixes = {NS_STREAMS: "stream"}
  400. self.authenticator = authenticator
  401. self.initializers = []
  402. self.features = {}
  403. # Reset the authenticator
  404. authenticator.associateWithStream(self)
  405. def _callLater(self, *args, **kwargs):
  406. from twisted.internet import reactor
  407. return reactor.callLater(*args, **kwargs)
  408. def reset(self):
  409. """
  410. Reset XML Stream.
  411. Resets the XML Parser for incoming data. This is to be used after
  412. successfully negotiating a new layer, e.g. TLS and SASL. Note that
  413. registered event observers will continue to be in place.
  414. """
  415. self._headerSent = False
  416. self._initializeStream()
  417. def onStreamError(self, errelem):
  418. """
  419. Called when a stream:error element has been received.
  420. Dispatches a L{STREAM_ERROR_EVENT} event with the error element to
  421. allow for cleanup actions and drops the connection.
  422. @param errelem: The received error element.
  423. @type errelem: L{domish.Element}
  424. """
  425. self.dispatch(
  426. failure.Failure(error.exceptionFromStreamError(errelem)), STREAM_ERROR_EVENT
  427. )
  428. self.transport.loseConnection()
  429. def sendHeader(self):
  430. """
  431. Send stream header.
  432. """
  433. # set up optional extra namespaces
  434. localPrefixes = {}
  435. for uri, prefix in self.prefixes.items():
  436. if uri != NS_STREAMS:
  437. localPrefixes[prefix] = uri
  438. rootElement = domish.Element(
  439. (NS_STREAMS, "stream"), self.namespace, localPrefixes=localPrefixes
  440. )
  441. if self.otherEntity:
  442. rootElement["to"] = self.otherEntity.userhost()
  443. if self.thisEntity:
  444. rootElement["from"] = self.thisEntity.userhost()
  445. if not self.initiating and self.sid:
  446. rootElement["id"] = self.sid
  447. if self.version >= (1, 0):
  448. rootElement["version"] = "%d.%d" % self.version
  449. self.send(rootElement.toXml(prefixes=self.prefixes, closeElement=0))
  450. self._headerSent = True
  451. def sendFooter(self):
  452. """
  453. Send stream footer.
  454. """
  455. self.send("</stream:stream>")
  456. def sendStreamError(self, streamError):
  457. """
  458. Send stream level error.
  459. If we are the receiving entity, and haven't sent the header yet,
  460. we sent one first.
  461. After sending the stream error, the stream is closed and the transport
  462. connection dropped.
  463. @param streamError: stream error instance
  464. @type streamError: L{error.StreamError}
  465. """
  466. if not self._headerSent and not self.initiating:
  467. self.sendHeader()
  468. if self._headerSent:
  469. self.send(streamError.getElement())
  470. self.sendFooter()
  471. self.transport.loseConnection()
  472. def send(self, obj):
  473. """
  474. Send data over the stream.
  475. This overrides L{xmlstream.XmlStream.send} to use the default namespace
  476. of the stream header when serializing L{domish.IElement}s. It is
  477. assumed that if you pass an object that provides L{domish.IElement},
  478. it represents a direct child of the stream's root element.
  479. """
  480. if domish.IElement.providedBy(obj):
  481. obj = obj.toXml(
  482. prefixes=self.prefixes,
  483. defaultUri=self.namespace,
  484. prefixesInScope=list(self.prefixes.values()),
  485. )
  486. xmlstream.XmlStream.send(self, obj)
  487. def connectionMade(self):
  488. """
  489. Called when a connection is made.
  490. Notifies the authenticator when a connection has been made.
  491. """
  492. xmlstream.XmlStream.connectionMade(self)
  493. self.authenticator.connectionMade()
  494. def onDocumentStart(self, rootElement):
  495. """
  496. Called when the stream header has been received.
  497. Extracts the header's C{id} and C{version} attributes from the root
  498. element. The C{id} attribute is stored in our C{sid} attribute and the
  499. C{version} attribute is parsed and the minimum of the version we sent
  500. and the parsed C{version} attribute is stored as a tuple (major, minor)
  501. in this class' C{version} attribute. If no C{version} attribute was
  502. present, we assume version 0.0.
  503. If appropriate (we are the initiating stream and the minimum of our and
  504. the other party's version is at least 1.0), a one-time observer is
  505. registered for getting the stream features. The registered function is
  506. C{onFeatures}.
  507. Ultimately, the authenticator's C{streamStarted} method will be called.
  508. @param rootElement: The root element.
  509. @type rootElement: L{domish.Element}
  510. """
  511. xmlstream.XmlStream.onDocumentStart(self, rootElement)
  512. # Setup observer for stream errors
  513. self.addOnetimeObserver("/error[@xmlns='%s']" % NS_STREAMS, self.onStreamError)
  514. self.authenticator.streamStarted(rootElement)
  515. class XmlStreamFactory(xmlstream.XmlStreamFactory):
  516. """
  517. Factory for Jabber XmlStream objects as a reconnecting client.
  518. Note that this differs from L{xmlstream.XmlStreamFactory} in that
  519. it generates Jabber specific L{XmlStream} instances that have
  520. authenticators.
  521. """
  522. protocol = XmlStream
  523. def __init__(self, authenticator):
  524. xmlstream.XmlStreamFactory.__init__(self, authenticator)
  525. self.authenticator = authenticator
  526. class XmlStreamServerFactory(xmlstream.BootstrapMixin, protocol.ServerFactory):
  527. """
  528. Factory for Jabber XmlStream objects as a server.
  529. @since: 8.2.
  530. @ivar authenticatorFactory: Factory callable that takes no arguments, to
  531. create a fresh authenticator to be associated
  532. with the XmlStream.
  533. """
  534. # Type is wrong. See: https://twistedmatrix.com/trac/ticket/10007#ticket
  535. protocol = XmlStream # type: ignore[assignment]
  536. def __init__(self, authenticatorFactory):
  537. xmlstream.BootstrapMixin.__init__(self)
  538. self.authenticatorFactory = authenticatorFactory
  539. def buildProtocol(self, addr):
  540. """
  541. Create an instance of XmlStream.
  542. A new authenticator instance will be created and passed to the new
  543. XmlStream. Registered bootstrap event observers are installed as well.
  544. """
  545. authenticator = self.authenticatorFactory()
  546. xs = self.protocol(authenticator)
  547. xs.factory = self
  548. self.installBootstraps(xs)
  549. return xs
  550. class TimeoutError(Exception):
  551. """
  552. Exception raised when no IQ response has been received before the
  553. configured timeout.
  554. """
  555. def upgradeWithIQResponseTracker(xs):
  556. """
  557. Enhances an XmlStream for iq response tracking.
  558. This makes an L{XmlStream} object provide L{IIQResponseTracker}. When a
  559. response is an error iq stanza, the deferred has its errback invoked with a
  560. failure that holds a L{StanzaError<error.StanzaError>} that is
  561. easier to examine.
  562. """
  563. def callback(iq):
  564. """
  565. Handle iq response by firing associated deferred.
  566. """
  567. if getattr(iq, "handled", False):
  568. return
  569. try:
  570. d = xs.iqDeferreds[iq["id"]]
  571. except KeyError:
  572. pass
  573. else:
  574. del xs.iqDeferreds[iq["id"]]
  575. iq.handled = True
  576. if iq["type"] == "error":
  577. d.errback(error.exceptionFromStanza(iq))
  578. else:
  579. d.callback(iq)
  580. def disconnected(_):
  581. """
  582. Make sure deferreds do not linger on after disconnect.
  583. This errbacks all deferreds of iq's for which no response has been
  584. received with a L{ConnectionLost} failure. Otherwise, the deferreds
  585. will never be fired.
  586. """
  587. iqDeferreds = xs.iqDeferreds
  588. xs.iqDeferreds = {}
  589. for d in iqDeferreds.values():
  590. d.errback(ConnectionLost())
  591. xs.iqDeferreds = {}
  592. xs.iqDefaultTimeout = getattr(xs, "iqDefaultTimeout", None)
  593. xs.addObserver(xmlstream.STREAM_END_EVENT, disconnected)
  594. xs.addObserver('/iq[@type="result"]', callback)
  595. xs.addObserver('/iq[@type="error"]', callback)
  596. directlyProvides(xs, ijabber.IIQResponseTracker)
  597. class IQ(domish.Element):
  598. """
  599. Wrapper for an iq stanza.
  600. Iq stanzas are used for communications with a request-response behaviour.
  601. Each iq request is associated with an XML stream and has its own unique id
  602. to be able to track the response.
  603. @ivar timeout: if set, a timeout period after which the deferred returned
  604. by C{send} will have its errback called with a
  605. L{TimeoutError} failure.
  606. @type timeout: C{float}
  607. """
  608. timeout = None
  609. def __init__(self, xmlstream, stanzaType="set"):
  610. """
  611. @type xmlstream: L{xmlstream.XmlStream}
  612. @param xmlstream: XmlStream to use for transmission of this IQ
  613. @type stanzaType: C{str}
  614. @param stanzaType: IQ type identifier ('get' or 'set')
  615. """
  616. domish.Element.__init__(self, (None, "iq"))
  617. self.addUniqueId()
  618. self["type"] = stanzaType
  619. self._xmlstream = xmlstream
  620. def send(self, to=None):
  621. """
  622. Send out this iq.
  623. Returns a deferred that is fired when an iq response with the same id
  624. is received. Result responses will be passed to the deferred callback.
  625. Error responses will be transformed into a
  626. L{StanzaError<error.StanzaError>} and result in the errback of the
  627. deferred being invoked.
  628. @rtype: L{defer.Deferred}
  629. """
  630. if to is not None:
  631. self["to"] = to
  632. if not ijabber.IIQResponseTracker.providedBy(self._xmlstream):
  633. upgradeWithIQResponseTracker(self._xmlstream)
  634. d = defer.Deferred()
  635. self._xmlstream.iqDeferreds[self["id"]] = d
  636. timeout = self.timeout or self._xmlstream.iqDefaultTimeout
  637. if timeout is not None:
  638. def onTimeout():
  639. del self._xmlstream.iqDeferreds[self["id"]]
  640. d.errback(TimeoutError("IQ timed out"))
  641. call = self._xmlstream._callLater(timeout, onTimeout)
  642. def cancelTimeout(result):
  643. if call.active():
  644. call.cancel()
  645. return result
  646. d.addBoth(cancelTimeout)
  647. self._xmlstream.send(self)
  648. return d
  649. def toResponse(stanza, stanzaType=None):
  650. """
  651. Create a response stanza from another stanza.
  652. This takes the addressing and id attributes from a stanza to create a (new,
  653. empty) response stanza. The addressing attributes are swapped and the id
  654. copied. Optionally, the stanza type of the response can be specified.
  655. @param stanza: the original stanza
  656. @type stanza: L{domish.Element}
  657. @param stanzaType: optional response stanza type
  658. @type stanzaType: C{str}
  659. @return: the response stanza.
  660. @rtype: L{domish.Element}
  661. """
  662. toAddr = stanza.getAttribute("from")
  663. fromAddr = stanza.getAttribute("to")
  664. stanzaID = stanza.getAttribute("id")
  665. response = domish.Element((None, stanza.name))
  666. if toAddr:
  667. response["to"] = toAddr
  668. if fromAddr:
  669. response["from"] = fromAddr
  670. if stanzaID:
  671. response["id"] = stanzaID
  672. if stanzaType:
  673. response["type"] = stanzaType
  674. return response
  675. @implementer(ijabber.IXMPPHandler)
  676. class XMPPHandler:
  677. """
  678. XMPP protocol handler.
  679. Classes derived from this class implement (part of) one or more XMPP
  680. extension protocols, and are referred to as a subprotocol implementation.
  681. """
  682. def __init__(self):
  683. self.parent = None
  684. self.xmlstream = None
  685. def setHandlerParent(self, parent):
  686. self.parent = parent
  687. self.parent.addHandler(self)
  688. def disownHandlerParent(self, parent):
  689. self.parent.removeHandler(self)
  690. self.parent = None
  691. def makeConnection(self, xs):
  692. self.xmlstream = xs
  693. self.connectionMade()
  694. def connectionMade(self):
  695. """
  696. Called after a connection has been established.
  697. Can be overridden to perform work before stream initialization.
  698. """
  699. def connectionInitialized(self):
  700. """
  701. The XML stream has been initialized.
  702. Can be overridden to perform work after stream initialization, e.g. to
  703. set up observers and start exchanging XML stanzas.
  704. """
  705. def connectionLost(self, reason):
  706. """
  707. The XML stream has been closed.
  708. This method can be extended to inspect the C{reason} argument and
  709. act on it.
  710. """
  711. self.xmlstream = None
  712. def send(self, obj):
  713. """
  714. Send data over the managed XML stream.
  715. @note: The stream manager maintains a queue for data sent using this
  716. method when there is no current initialized XML stream. This
  717. data is then sent as soon as a new stream has been established
  718. and initialized. Subsequently, L{connectionInitialized} will be
  719. called again. If this queueing is not desired, use C{send} on
  720. C{self.xmlstream}.
  721. @param obj: data to be sent over the XML stream. This is usually an
  722. object providing L{domish.IElement}, or serialized XML. See
  723. L{xmlstream.XmlStream} for details.
  724. """
  725. self.parent.send(obj)
  726. @implementer(ijabber.IXMPPHandlerCollection)
  727. class XMPPHandlerCollection:
  728. """
  729. Collection of XMPP subprotocol handlers.
  730. This allows for grouping of subprotocol handlers, but is not an
  731. L{XMPPHandler} itself, so this is not recursive.
  732. @ivar handlers: List of protocol handlers.
  733. @type handlers: C{list} of objects providing
  734. L{IXMPPHandler}
  735. """
  736. def __init__(self):
  737. self.handlers = []
  738. def __iter__(self):
  739. """
  740. Act as a container for handlers.
  741. """
  742. return iter(self.handlers)
  743. def addHandler(self, handler):
  744. """
  745. Add protocol handler.
  746. Protocol handlers are expected to provide L{ijabber.IXMPPHandler}.
  747. """
  748. self.handlers.append(handler)
  749. def removeHandler(self, handler):
  750. """
  751. Remove protocol handler.
  752. """
  753. self.handlers.remove(handler)
  754. class StreamManager(XMPPHandlerCollection):
  755. """
  756. Business logic representing a managed XMPP connection.
  757. This maintains a single XMPP connection and provides facilities for packet
  758. routing and transmission. Business logic modules are objects providing
  759. L{ijabber.IXMPPHandler} (like subclasses of L{XMPPHandler}), and added
  760. using L{addHandler}.
  761. @ivar xmlstream: currently managed XML stream
  762. @type xmlstream: L{XmlStream}
  763. @ivar logTraffic: if true, log all traffic.
  764. @type logTraffic: C{bool}
  765. @ivar _initialized: Whether the stream represented by L{xmlstream} has
  766. been initialized. This is used when caching outgoing
  767. stanzas.
  768. @type _initialized: C{bool}
  769. @ivar _packetQueue: internal buffer of unsent data. See L{send} for details.
  770. @type _packetQueue: C{list}
  771. """
  772. logTraffic = False
  773. def __init__(self, factory):
  774. XMPPHandlerCollection.__init__(self)
  775. self.xmlstream = None
  776. self._packetQueue = []
  777. self._initialized = False
  778. factory.addBootstrap(STREAM_CONNECTED_EVENT, self._connected)
  779. factory.addBootstrap(STREAM_AUTHD_EVENT, self._authd)
  780. factory.addBootstrap(INIT_FAILED_EVENT, self.initializationFailed)
  781. factory.addBootstrap(STREAM_END_EVENT, self._disconnected)
  782. self.factory = factory
  783. def addHandler(self, handler):
  784. """
  785. Add protocol handler.
  786. When an XML stream has already been established, the handler's
  787. C{connectionInitialized} will be called to get it up to speed.
  788. """
  789. XMPPHandlerCollection.addHandler(self, handler)
  790. # get protocol handler up to speed when a connection has already
  791. # been established
  792. if self.xmlstream and self._initialized:
  793. handler.makeConnection(self.xmlstream)
  794. handler.connectionInitialized()
  795. def _connected(self, xs):
  796. """
  797. Called when the transport connection has been established.
  798. Here we optionally set up traffic logging (depending on L{logTraffic})
  799. and call each handler's C{makeConnection} method with the L{XmlStream}
  800. instance.
  801. """
  802. def logDataIn(buf):
  803. log.msg("RECV: %r" % buf)
  804. def logDataOut(buf):
  805. log.msg("SEND: %r" % buf)
  806. if self.logTraffic:
  807. xs.rawDataInFn = logDataIn
  808. xs.rawDataOutFn = logDataOut
  809. self.xmlstream = xs
  810. for e in self:
  811. e.makeConnection(xs)
  812. def _authd(self, xs):
  813. """
  814. Called when the stream has been initialized.
  815. Send out cached stanzas and call each handler's
  816. C{connectionInitialized} method.
  817. """
  818. # Flush all pending packets
  819. for p in self._packetQueue:
  820. xs.send(p)
  821. self._packetQueue = []
  822. self._initialized = True
  823. # Notify all child services which implement
  824. # the IService interface
  825. for e in self:
  826. e.connectionInitialized()
  827. def initializationFailed(self, reason):
  828. """
  829. Called when stream initialization has failed.
  830. Stream initialization has halted, with the reason indicated by
  831. C{reason}. It may be retried by calling the authenticator's
  832. C{initializeStream}. See the respective authenticators for details.
  833. @param reason: A failure instance indicating why stream initialization
  834. failed.
  835. @type reason: L{failure.Failure}
  836. """
  837. def _disconnected(self, reason):
  838. """
  839. Called when the stream has been closed.
  840. From this point on, the manager doesn't interact with the
  841. L{XmlStream} anymore and notifies each handler that the connection
  842. was lost by calling its C{connectionLost} method.
  843. """
  844. self.xmlstream = None
  845. self._initialized = False
  846. # Notify all child services which implement
  847. # the IService interface
  848. for e in self:
  849. e.connectionLost(reason)
  850. def send(self, obj):
  851. """
  852. Send data over the XML stream.
  853. When there is no established XML stream, the data is queued and sent
  854. out when a new XML stream has been established and initialized.
  855. @param obj: data to be sent over the XML stream. See
  856. L{xmlstream.XmlStream.send} for details.
  857. """
  858. if self._initialized:
  859. self.xmlstream.send(obj)
  860. else:
  861. self._packetQueue.append(obj)
  862. __all__ = [
  863. "Authenticator",
  864. "BaseFeatureInitiatingInitializer",
  865. "ConnectAuthenticator",
  866. "FeatureNotAdvertized",
  867. "INIT_FAILED_EVENT",
  868. "IQ",
  869. "ListenAuthenticator",
  870. "NS_STREAMS",
  871. "NS_XMPP_TLS",
  872. "Reset",
  873. "STREAM_AUTHD_EVENT",
  874. "STREAM_CONNECTED_EVENT",
  875. "STREAM_END_EVENT",
  876. "STREAM_ERROR_EVENT",
  877. "STREAM_START_EVENT",
  878. "StreamManager",
  879. "TLSError",
  880. "TLSFailed",
  881. "TLSInitiatingInitializer",
  882. "TLSNotSupported",
  883. "TLSRequired",
  884. "TimeoutError",
  885. "XMPPHandler",
  886. "XMPPHandlerCollection",
  887. "XmlStream",
  888. "XmlStreamFactory",
  889. "XmlStreamServerFactory",
  890. "hashPassword",
  891. "toResponse",
  892. "upgradeWithIQResponseTracker",
  893. ]