xmlstream.py 35 KB

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